pandas-21 Series和Dataframe的畫圖方法
前言
在pandas中,無論是series還是dataframe都內置了.plot()方法,可以結合plt.show()進行很方便的畫圖。
Series.plot() 和 Dataframe.plot()參數
data : Series
kind : str
‘line’ : line plot (default)
‘bar’ : vertical bar plot
‘barh’ : horizontal bar plot
‘hist’ : histogram
‘box’ : boxplot
‘kde’ : Kernel Density Estimation plot
‘density’ : same as ‘kde’
‘area’ : area plot
‘pie’ : pie plot
指定畫圖的類型,是線形圖還是柱狀圖等
label 添加標簽
title 添加標題
……(后接一大堆可選參數)
詳情請查閱:[官方文檔傳送門](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.plot.html?highlight=series plot#pandas.Series.plot)
Dataframe.plot()參數 也是大同小異:
詳情請查閱:官方文檔傳送門
Series.plot()代碼demo
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas import Series
# 創建一個隨機種子, 把生成的值固定下來
np.random.seed(666)
s1 = Series(np.random.randn(1000)).cumsum()
s2 = Series(np.random.randn(1000)).cumsum()
# series 中 也包含了 plot 方法
s1.plot(kind = 'line', grid = True, label = 'S1', title = 'xxx')
s2.plot(label = 's2')
plt.legend()
plt.show() # 圖1
# 通過 子圖的 方式,可視化 series
figure, ax = plt.subplots(2, 1)
ax[0].plot(s1)
ax[1].plot(s2)
plt.legend()
plt.show() # 圖2
# 通過 series中的plot方法進行指定是哪一個子圖
fig, ax = plt.subplots(2, 1)
s1.plot(ax = ax[1], label = 's1')
s2.plot(ax = ax[0], label = 's2')
plt.legend()
plt.show() # 圖3
1234567891011121314151617181920212223242526272829303132333435
圖1:
圖2:
圖3:
Dataframe.plot()代碼demo
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series, DataFrame
np.random.seed(666)
df = DataFrame(
np.random.randint(1, 10, 40).reshape(10, 4),
columns = ['A', 'B', 'C', 'D']
)
print(df)
'''
A B C D
0 3 7 5 4
1 2 1 9 8
2 6 3 6 6
3 5 9 5 5
4 1 1 5 1
5 5 6 8 2
6 1 1 7 7
7 1 4 3 3
8 7 1 7 1
9 4 7 4 3
'''
# Dataframe 也有個內置方法 plot
df.plot(kind = 'bar') # kind = 'bar'
plt.show() # 圖1
# 橫向的柱狀圖
df.plot(kind = 'barh') # kind = 'barh' 可以是一個橫向的柱狀圖
plt.show() # 圖2
# 將每個column的柱狀圖堆疊起來
df.plot(kind = 'bar', stacked = True)
plt.show() # 圖3
# 填充的圖
df.plot(kind = 'area')
plt.show() # 圖4
# 可以進行選擇
b = df.iloc[6] # 這時候的b是一個series
b.plot() # 可以看出x軸就是colume的name
plt.show() # 圖5
# 可以將所有的行全部畫在一張圖里
for i in df.index:
df.iloc[i].plot(label = str(i))
plt.legend()
plt.show() # 圖6
# 對一列進行畫圖
df['A'].plot()
plt.show() # 圖7
# 多列畫圖,同上
# 注意:默認是按照column來進行畫圖的,
# 如果需要按照 index 畫圖,可以將 dataframe 轉置一下
df.T.plot()
plt.show() # 圖8
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
圖1:
圖2:
圖3:
圖4:
圖5:
圖6:
圖7:
圖8: