matplotlib + pandas——資料視覺化
阿新 • • 發佈:2019-01-22
1 第一個繪圖
(原本在matplotlib中需要幾段程式碼,在pandas中只需要一行程式碼)
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Series 預設索引為x軸 s = pd.Series( np.random.randn(10).cumsum() #產生一個10行4列的隨機數 index = np.arange(0
,100,10) #0-100之間,以10作為分割 ) s.plot() plt.show()
2 pandas利用DataFrame的plot方法繪圖
df = pd.DataFrame(np.random.randn(10,4), #生成10行4列標準正態分佈的資料 columns = list('ABCD'), index = np.range(0,100,10) #指定索引為 x 軸 ) pd.plot() plt.show()
修改 pd.plot(subplots = True) #將4個數據分配到不同的畫布
3 pandas利用DataFrame繪圖柱狀圖/堆積圖(載入csv資料)
案例1 fig = plt.figure() fig,axes = plt.subplots(2,1) data = pd.Series(np.random.randn(16), index = list('abcdefghijklmnop')) data.plot(kind = 'bar',ax = axes[0],color = 'k',alpha = 0.7) data.plot(kind = 'barh',ax = axes[1],color = 'k',alpha = 0.7) plt
.show()
案例2 pd = pd.read_csv('flights.csv') #匯入資料(注意觀察資料格式) number = pd["passengers"].groupby([pd["year"],pd["month"]]).sum().unstack() number.plot(kind="bar",figsize=(23,8))
flights.csv 檔案(由於網頁不能匯入檔案,這裡只是展示一部分資料)
year month passengers 0 1949 January 112 1 1949 February 118 2 1949 March 132 3 1949 April 129 4 1949 May 121 5 1949 June 135 6 1949 July 148 7 1949 August 148 8 1949 September 136 … … … … 138 1960 July 622 139 1960 August 606 140 1960 September 508 141 1960 October 461 142 1960 November 390 143 1960 December 432
4 pandas繪圖頻率直方圖(載入csv檔案)
df = pd.read_excel('./pandas-matplotlib.xlsx','Sheet1') #匯入資料檔案 fig = plt.figure() # 建立畫板 ax = fig.add_subplot(111) # 建立繪圖區域 fig.set_size_inches(10,5) # 設定已建立畫布大小 ax.hist(df['Age'],bins = 7) # 繪製頻率直方圖 plt.title('年齡平均分佈圖') plt.xlabel('Age') plt.ylabel('Employee') plt.show()
pandas-matplotlib.xlsx中 Sheet1 資料如下:
EMPID Gender Age Sales BMI Income E001 M 34 123 Normal 350 E002 F 40 114 Overweight 450 E003 F 37 135 Obesity 169 E004 M 30 139 Underweight 189 E005 F 44 117 Underweight 183 E006 M 36 121 Normal 80 E007 M 32 133 Obesity 166 E008 F 26 140 Normal 120 E009 M 32 133 Normal 75 E010 M 36 133 Underweight 40
5 pandas繪圖箱型圖
df = pd.read_excel('./pandas-matplotlib.xlsx','Sheet1') #匯入資料檔案
fig = plt.figure()
ax = fig.add_subplot(111)
ax.boxplot(df['Age']) #繪製箱型圖
plt.show()
6 利用pandas 處理後的資料繪圖
6.1◆條形圖
var = df.groupby('Gender').Sales.sum() fig = plt.figure() ax1 = fig.add_subplot(211) ax1.set_xlabel('Gender') ax1.set_ylabel('Sum of Sales') ax1.set_title('Gender wise Sum of Sales') var.plot(kind = 'bar')
6.2◆折線圖
line = df.groupby('BMI').Sales.sum() #print(line) ax1 = fig.add_subplot(212) ax1.set_xlabel('BMI') ax1.set_ylabel('Sum of Sales') ax1.set_title('BMI wise Sum of Sales') line.plot(kind = 'line') plt.tight_layout() plt.show()
7 利用pandas 繪製柱狀堆積圖
df = pd.read_excel('./excel/pandas-matplotlib.xlsx','Sheet1') #匯入資料檔案 fig = plt.figure() var = df.groupby(['BMI', 'Gender']).Sales.sum() var.unstack().plot(kind='bar', stacked=True, color=['red', 'blue']) plt.show()
8 利用pandas 繪製點狀圖
8.1◆繪製 散點圖
fig = plt.figure() ax1 = fig.add_subplot(111) ax.scatter(df['Age'],df[Sales]) plt.show()
8.2◆繪製 氣泡圖
df = pd.read_excel('./excel/pandas-matplotlib.xlsx','Sheet1') #匯入資料檔案 fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(df['Age'], df['Sales'], s=df['Income']) #在散點圖上新增第三個引數:表明收入(氣泡的大小) plt.show()
9 利用pandas 繪製餅圖
var = df.groupby(['Gender']).sum() x_list = var['Sales'] label_list = var.index plt.axis('equal') plt.pie(x_list, labels=label_list, autopct='%1.1f%%', # 保留兩位小時 shadow = True, # 設定陰影 explode=[0,0.1]) # 0 :扇形不分離,0.1:分離0.1單位 plt.title('expense') plt.show()