Python實現條形圖的繪製
Python實現條形圖的繪製:
說明:程式碼執行環境:Win10+Python3+jupyter notebook
條形圖是一種用來描繪已彙總的分型別資料的頻數分佈、相對頻數分佈或百分數頻數分佈。(百分數頻數就是相對頻數乘以100%)
方法1:pandas中的Series物件或者DataFrame物件呼叫plot()或plot.bar()、plot.barh()方法;
Series.plot()用法:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html#pandas.Series.plot
DataFrame.plot()的用法:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html
Series.plot.bar()的用法:
DataFrame.plot.bar()的用法:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html
具體示例:
匯出要用到的相關包:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
Series.plot.bar()示例:
fig,axes = plt.subplots(2,1) data = pd.Series(np.random.rand(16),index=list('abcdefghijklmnop')) data.plot.bar(ax=axes[0],color='k',alpha=0.7,rot=0) data.plot.barh(ax=axes[1],color='k',alpha=0.7) plt.savefig('p4.png')
上述程式碼的輸出結果是:
採用axes[].set_······()方法對子圖中的各種元素進行設定。
具體參見官方文件:
https://matplotlib.org/api/axes_api.html?highlight=axes#module-matplotlib.axes
如何調整上圖中第二個子圖縱軸上標籤之間的間距?
解決方法是將增大figure的尺寸,可以手動調整,也可以通過程式碼調整。
DataFrame.plot.bar()示例:
# 建立一個DataFrame物件
df = pd.DataFrame(np.random.rand(6,4),
index=['one','two','three','four','five','six'],
columns=pd.Index(['A','B','C','D'],name='Genus'))
fig,axes = plt.subplots(1,1)
df.plot.bar(ax=axes,stacked=True,alpha=0.7,rot=0) # stacked=True時繪製的是堆積條形圖
axes.set_title('The first bar plot')
plt.savefig('p5.png')
# bar繪製的垂直方向的條形圖,barh繪製的是水平的條形圖
上述程式碼的輸出結果為:
同理,上圖中的各個元素可以通過呼叫axes.set_······()來設定。
如果上述程式碼中的df.plot.bar改為df.plot.barh則原條形圖變為:
方法2:從seaborn包中呼叫barplot()方法。
具體示例:
seaborn.barplot()示例:
data = {'state':['Ohio','Nevada','Ohio','Nevada'],
'year':[2000,2000,2001,2001],
'pop':[1.5,1.7,1.8,2.5]}
frame = pd.DataFrame(data)
fig,axes = plt.subplots(2,1)
sns.barplot(x='state',y='pop',hue='year',data=frame,ax=axes[0],orient='v')
sns.barplot(x='pop',y='state',hue='year',data=frame,ax=axes[1],orient='h')
plt.savefig('p7.png')
#當要繪製水平方向的條形圖時注意要交換x與y所表示的值
上述程式碼地輸出結果是:
同理,上圖中的各個元素可以通過呼叫axes[].set_······()來設定。
如何調整上圖中各個subplot之間的間距?
可以使用pyplot.subplots_adjust()方法調整,具體可參見官方文件:
參考資料:
《利用Python進行資料分析》第二版
《商務與經濟統計》第十三版
matplotlib、seaborn、pandas官方文件
PS1:打算寫一個Python實現常用圖表的系列,這個系列所採用的繪圖方式是通過subplot的示例來呼叫繪製各種圖形的方法,我把它理解成面對物件式繪圖,與此相對的是函式式繪圖,通過matplotlib.pyplot來呼叫繪製各種圖形的函式。
PS2:本文是博主的第一篇部落格,難免有疏漏之處,歡迎交流討論