Pandas 內置的十種畫圖方法
前言
Pandas是非常常見的數據分析工具,我們一般都會處理好處理數據然后使用searbon或matplotlib來進行繪制。但在Pandas內部就已經集成了matplotlib,本文將展示Pandas內部的畫圖方法。
畫圖類型
在Pandas中內置的畫圖方法如下幾類,基本上都是常見的畫圖方法。每種方法底層也是使用的matplotlib。
line : line plot (default)
bar : vertical bar plot
barh : horizontal bar plot
hist : histogram
box : boxplot
density/kde : Density Estimation
area : area plot
pie : pie plot
scatter : scatter plot
hexbin : hexbin plot
在進行畫圖時我們有兩種調用方法:
df = pd.DataFrame({
'sales': [3, 3, 3, 9, 10, 6],
'signups': [4, 5, 6, 10, 12, 13],
'visits': [20, 42, 28, 62, 81, 50],
}, index=pd.date_range(start='2018/01/01', end='2018/07/01', freq='M'))
# 方法1,這種方法是高層API,需要制定kind
df.plot(kind='area')
# 方法2,這種方法是底層API
df.plot.area()
面積圖(area)
面積圖直觀地顯示定量數據下面的區(qū)域面積,該函數包裝了 matplotlib 的area函數。
# 默認為面積堆疊 df.plot(kind='area')

# 設置面積不堆疊 df.plot.area(stacked=False)

# 手動指定坐標軸 df.plot.area(y='sales', x='signups')

條形圖(bar)
條形圖是一種用矩形條顯示分類數據的圖,矩形條的長度與它們所代表的值成比例。條形圖顯示離散類別之間的比較。圖的一個軸顯示比較的特定類別,另一個軸表示測量值。
df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
# 手動設置坐標軸
ax = df.plot.bar(x='lab', y='val', rot=0)
# 并排繪制 df.plot.bar(rot=0)

# 堆疊繪制 df.plot.bar(stacked=True)

# 分圖繪制 axes = df.plot.bar(rot=0, subplots=True) axes[0].legend(loc=2) axes[1].legend(loc=2)

水平條形圖(barh)
水平條形圖是用矩形條形表示定量數據的圖表,矩形條形的長度與它們所代表的值成正比。條形圖顯示離散類別之間的比較。
# 并排繪制 df.plot.barh(rot=0)

# 堆疊繪制 df.plot.barh(stacked=True)

箱線圖(boxplot)
箱線圖是一種通過四分位數以圖形方式描繪數值數據組的方法。該框從數據的 Q1 到 Q3 四分位值延伸,在中位數 (Q2) 處有一條線。
age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]
df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list})
ax = df.plot.box(column="age", by="gender", figsize=(10, 8))
密度圖(density)
核密度估計 (KDE) 是一種估計隨機變量的概率密度函數 (PDF) 的非參數方法。
s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5]) ax = s.plot.kde()

df = pd.DataFrame({
'x': [1, 2, 2.5, 3, 3.5, 4, 5],
'y': [4, 4, 4.5, 5, 5.5, 6, 6],
})
ax = df.plot.kde()
六邊形圖(hexbin)
和熱力圖類似,具體的顏色按照密度來進行展示。但形狀使用六邊形圖代替。
n = 10000
df = pd.DataFrame({'x': np.random.randn(n),
'y': np.random.randn(n)})
ax = df.plot.hexbin(x='x', y='y', gridsize=20)
直方圖(hist)
df = pd.DataFrame(
np.random.randint(1, 7, 6000),
columns = ['one'])
df['two'] = df['one'] + np.random.randint(1, 7, 6000)
ax = df.plot.hist(bins=12, alpha=0.5)
折線圖(line)
s = pd.Series([1, 3, 2]) s.plot.line()

df = pd.DataFrame({
'pig': [20, 18, 489, 675, 1776],
'horse': [4, 25, 281, 600, 1900]
}, index=[1990, 1997, 2003, 2009, 2014])
lines = df.plot.line()
餅圖(pie)
df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(5, 5))
# 默認使用index進行分組 df.plot.pie(subplots=True, figsize=(11, 6))

散點圖(scatter)
df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
[6.4, 3.2, 1], [5.9, 3.0, 2]],
columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',y='width', c='DarkBlue')
到此這篇關于Pandas 內置的十種畫圖方法的文章就介紹到這了,更多相關Pandas 內置畫圖方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

