在pandas中,我們有行標籤、列標籤以及分組信息。也就是說,要製作一張完整的圖表,原本需要一大堆的matplotlib代碼,現在只需一兩條簡潔的語句就可以了。pandas有許多能夠利用DataFrame對象數據組織特點來創建標準圖標的高級繪圖方法(這些函數的數量還在不斷增加)。
一,利用Series的plot方法繪圖
用Series繪圖的原理:Series的索引作爲x軸,Series的值作爲y軸
from matplotlib import pyplot as plt
import numpy as np
from pandas import DataFrame,Series
import pandas as pd
#用來正常顯示中文標籤
plt.rcParams['font.sans-serif']=['SimHei']
#用來正常顯示負號
plt.rcParams['axes.unicode_minus']=False
#1.利用隨機函數創建一組隨機序列
series = Series(np.random.randn(10).cumsum()) #數據集累計和
series
#利用series默認的index作爲x軸數據,series的value作爲y軸值
axes = series.plot(label="折線圖",style='ko-')
axes.set_title("利用Series繪製折線圖")
axes.legend()
結果顯示:
#2.也可以指定series的index的值作爲x軸
Index = np.arange(0,100,10)
series1 = Series(np.random.randn(10).cumsum(),index = Index) #數據集累計和
series1
#打印結果:
0 0.377990
10 1.637537
20 1.325206
30 0.376472
40 0.284113
50 1.102053
60 2.342911
70 3.119967
80 4.412816
90 4.505813
dtype: float64
#利用series指定的index值作爲x軸數據,series的value作爲y軸值
axes = series1.plot(label="折線圖")
axes.set_title("利用Series繪製折線圖")
axes.legend()
結果顯示:
二,利用DataFrame的plot方法繪圖
df = DataFrame(np.random.randn(10,4),
columns=list('ABCD'),
index=np.arange(0,100,10))
#Dataframe繪圖,每一列繪製一組折線圖
df.plot()
plt.show()
結果顯示:
df.plot(subplots=True)
結果顯示:
df.plot(subplots=True,sharey=True)
結果顯示:
#創建畫板獲取axes對象
fig,ax = plt.subplots(2,1,figsize=(10,10))
# fig.set_size_inches(10,7) #修改已創建子畫板大小
#創建繪圖數據
data = Series(np.random.randn(16),
index=list('abcdefghijklmnop'))
#利用series數據在2行一列的畫板上的第一塊區域繪製柱狀圖,每一行都是一條數據
data.plot(kind='bar',ax=ax[0],color='k',alpha=0.7) #alpha表示圖表的填充透明度
#利用series數據在2行一列的畫板上的第二塊區域繪製條形圖
data.plot(kind='barh',ax=ax[1],color='g',alpha=0.5)
打印結果:
三,pandas讀取excel文件
df = pd.read_excel("excel/pandas-matplotlib.xlsx","Sheet1")
df
結果顯示:
#創建一個空白畫板
figure = plt.figure()
#在畫板上添加一個axes繪圖區域
ax = figure.add_subplot(111)
#在選中的區域裏繪直方圖
ax.hist(df['Age'],bins=7)
plt.title('Age distribution')
plt.xlabel('Age')
plt.ylabel('Employee')
plt.show()
結果顯示:
#繪製箱線圖
figure = plt.figure()
ax = figure.add_subplot(111)
#根據年齡繪製箱線圖
ax.boxplot(df.Age)
plt.show()
結果顯示:
df.Age.describe()
#打印結果:
count 10.000000
mean 34.700000
std 5.121849
min 26.000000
25% 32.000000
50% 35.000000
75% 36.750000
max 44.000000
Name: Age, dtype: float64
#按照性別分類後統計銷量總和
var = df.groupby('Gender').Sales.sum()
var
#打印結果:
Gender
F 506
M 782
Name: Sales, dtype: int64
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel('Gerder')
ax1.set_ylabel('Sun of Sales')
ax1.set_title('Gender wise Sum of Sales')
#繪製柱狀圖
var.plot(kind='bar')
結果顯示:
#根據BMI分組
var = df.groupby("BMI").Sales.sum()
print(var)
#打印結果:
BMI
Normal 517
Obesity 268
Overweight 114
Underweight 389
Name: Sales, dtype: int64
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel("BMI")
ax.set_ylabel("Sum of Sales")
ax.set_title('BMI wise Sum of Sales')
var.plot(kind='line')
plt.show()
結果顯示:
#按照身體指數和性別分組後統計銷售數量
var = df.groupby(['BMI','Gender']).Sales.sum()
result = var.unstack()
result
打印結果:
#繪製柱狀圖
result.plot(kind='bar')
結果顯示:
#繪製堆積圖
result.plot(kind='bar',stacked=True,color=['r','b'])
plt.show()
結果顯示:
#繪製散點圖
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(df['Age'],df['Sales'])
plt.show()
結果顯示:
#繪製氣泡圖
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(df['Age'],df['Sales'],s=df['Income']) #第三個變量表明根據收入氣泡的大小
plt.show()
結果顯示:
#繪製餅圖
var = df.groupby(['Gender']).sum()
var
結果顯示:
x_list = var['Sales']
label_list = var.index
plt.axis('equal')
plt.pie(x_list, labels=label_list,
startangle=90,
shadow = True, #是否顯示陰影
explode =[0.05,0],
autopct='%1.1f%%')
plt.title('expense')
plt.show()
結果顯示: