python 中多图形组合
一、多图形组合参数详解
plt.subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs)
- shape:指定组合图的框架形状,以元组形式传递,如2×3的矩阵可以表示成(2,3)
- loc:指定子图所在的位置,如shape中第一行第一列可以表示成(0,0)
- rowspan:指定某个子图需要跨几行
- colspan:指定某个子图需要跨几列
1 # 读取数据 2 Prod_Trade = pd.read_excel('Prod_Trade.xlsx') 3 # 衍生出交易年份和月份字段 4 Prod_Trade['year'] = Prod_Trade.Date.dt.year 5 Prod_Trade['month'] = Prod_Trade.Date.dt.month 6 7 # 设置大图框的长和高 8 plt.figure(figsize = (12,6)) 9 # 设置第一个子图的布局 10 ax1 = plt.subplot2grid(shape = (2,3), loc = (0,0)) 11 # 统计2012年各订单等级的数量 12 Class_Counts = Prod_Trade.Order_Class[Prod_Trade.year == 2012].value_counts() 13 Class_Percent = Class_Counts/Class_Counts.sum() 14 # 将饼图设置为圆形(否则有点像椭圆) 15 ax1.set_aspect(aspect = 'equal') 16 # 绘制订单等级饼图 17 ax1.pie(x = Class_Percent.values, labels = Class_Percent.index, autopct = '%.1f%%') 18 # 添加标题 19 ax1.set_title('各等级订单比例') 20 21 # 设置第二个子图的布局 22 ax2 = plt.subplot2grid(shape = (2,3), loc = (0,1)) 23 # 统计2012年每月销售额 24 Month_Sales = Prod_Trade[Prod_Trade.year == 2012].groupby(by = 'month').aggregate({'Sales':np.sum}) 25 # 绘制销售额趋势图 26 Month_Sales.plot(title = '2012年各月销售趋势', ax = ax2, legend = False) 27 # 删除x轴标签 28 ax2.set_xlabel('') 29 30 # 设置第三个子图的布局 31 ax3 = plt.subplot2grid(shape = (2,3), loc = (0,2), rowspan = 2) 32 # 绘制各运输方式的成本箱线图 33 sns.boxplot(x = 'Transport', y = 'Trans_Cost', data = Prod_Trade, ax = ax3) 34 # 添加标题 35 ax3.set_title('各运输方式成本分布') 36 # 删除x轴标签 37 ax3.set_xlabel('') 38 # 修改y轴标签 39 ax3.set_ylabel('运输成本') 40 41 # 设置第四个子图的布局 42 ax4 = plt.subplot2grid(shape = (2,3), loc = (1,0), colspan = 2) 43 # 2012年客单价分布直方图 44 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'})) 45 # 添加标题 46 ax4.set_title('2012年客单价分布图') 47 # 修改x轴标签 48 ax4.set_xlabel('销售额') 49 50 # 调整子图之间的水平间距和高度间距 51 plt.subplots_adjust(hspace=0.6, wspace=0.3) 52 # 图形显示 53 plt.show()
浙公网安备 33010602011771号