多個圖形的合并

通過matplotlib模塊中的subplot2grid函數(shù),可以是m*n的矩陣風格,也可以是跨行或跨列的矩陣風格

# 讀取數(shù)據(jù)
Prod_Trade = pd.read_excel(r'F:\Prod_Trade.xlsx')
Prod_Trade.head()

以某集市商品交易數(shù)據(jù)為例


# 衍生出交易年份和月份字段
Prod_Trade['year'] = Prod_Trade.Date.dt.year
Prod_Trade['month'] = Prod_Trade.Date.dt.month
#再次查看數(shù)據(jù)
Prod_Trade.head()
# 設置大圖框的長和高
plt.figure(figsize = (12,6))
# 設置第一個子圖的布局
ax1 = plt.subplot2grid(shape = (2,3), loc = (0,0))
# 統(tǒng)計2012年各訂單等級的數(shù)量
Class_Counts = Prod_Trade.Order_Class[Prod_Trade.year == 2012].value_counts()
Class_Percent = Class_Counts/Class_Counts.sum()
# 將餅圖設置為圓形(否則有點像橢圓)
ax1.set_aspect(aspect = 'equal')
# 繪制訂單等級餅圖
ax1.pie(x = Class_Percent.values, labels = Class_Percent.index, autopct = '%.1f%%')
# 添加標題
ax1.set_title('各等級訂單比例')

# 設置第二個子圖的布局
ax2 = plt.subplot2grid(shape = (2,3), loc = (0,1))
# 統(tǒng)計2012年每月銷售額
Month_Sales = Prod_Trade[Prod_Trade.year == 2012].groupby(by = 'month').aggregate({'Sales':np.sum})
# 繪制銷售額趨勢圖
Month_Sales.plot(title = '2012年各月銷售趨勢', ax = ax2, legend = False)
# 刪除x軸標簽
ax2.set_xlabel('')

# 設置第三個子圖的布局
ax3 = plt.subplot2grid(shape = (2,3), loc = (0,2), rowspan = 2)
# 繪制各運輸方式的成本箱線圖
sns.boxplot(x = 'Transport', y = 'Trans_Cost', data = Prod_Trade, ax = ax3)
# 添加標題
ax3.set_title('各運輸方式成本分布')
# 刪除x軸標簽
ax3.set_xlabel('')
# 修改y軸標簽
ax3.set_ylabel('運輸成本')

# 設置第四個子圖的布局
ax4 = plt.subplot2grid(shape = (2,3), loc = (1,0), colspan = 2)
# 2012年客單價分布直方圖
sns.distplot(Prod_Trade.Sales[Prod_Trade.year == 2012], bins = 40, norm_hist = True, ax = ax4, hist_kws = {'color':'steelblue'}, kde_kws=({'linestyle':'--', 'color':'red'}))
# 添加標題
ax4.set_title('2012年客單價分布圖')
# 修改x軸標簽
ax4.set_xlabel('銷售額')

# 調(diào)整子圖之間的水平間距和高度間距
plt.subplots_adjust(hspace=0.6, wspace=0.3)
# 圖形顯示
plt.show()

繪制每一幅子圖之前,運用subplot2grid函數(shù)控制子圖的位置,傳遞給ax1,ax2..
為子圖添加標題等,需要單獨指定


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容