matplotlib 中可以做多图合并的函数有 add_subplot 、 subplot 、subplot2grid, 想要画跨行或跨列图时用 subplot2grid 很方便,如果是每个图都均分则推荐用add_subplot 或 subplot

设置显示中文:

plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
plt.rcParams['axes.unicode_minus'] = False   # 步骤二(解决坐标轴负数的负号显示问题)
plt.rcParams['savefig.dpi'] = 150 #保存的图片像素
plt.rcParams['figure.dpi'] = 150 #画布中显示的图片分辨率

1、subplot2grid 函数用法及参数说明:

subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)

shape : 组合图框架形状,以元组形式传递,如2行3列可以表示为(2,3)

loc : 指定子图所在位置,如第一个位置是(0,0)

rowspan :指定子图需要跨几行

colspan : 指定子图需要跨几列

以 2 x 3 布局为例,说明子图位置与跨行、跨列问题:

Python matplotlib 画两条线 matplotlib画两个图_组合图

# 设置大图框的长和高
plt.figure(figsize = (12,6))
# 设置第一个子图的布局
ax1 = plt.subplot2grid(shape = (2,3), loc = (0,0))
# 统计2012年各订单等级的数量
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))
# 统计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('销售额')

# 调整子图之间的水平间距和高度间距
plt.subplots_adjust(hspace=0.6, wspace=0.3)
# 图形显示
plt.show()

效果图:

Python matplotlib 画两条线 matplotlib画两个图_subplor_02

2、add_subplot 及 subplot

两个函数参数一样:
add_subplot(rows,cols,loc,sharex,sharey)
cows: 行数
cols : 列数
loc : 位置 (位置计数在画布中从左到右,从上到下,如下2,2画布中)
sharex: 所有子图共用一条x轴
sharey:所有子图共用一条y轴

1

2

3

4

add_subplot 实例

x=np.linspace(1,100,2)
fig=plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.plot(x, x)
ax2 = fig.add_subplot(222)
ax2.plot(x, -x)
ax3 = fig.add_subplot(223)
ax3.plot(x, x ** 2)
ax4 = fig.add_subplot(224)
ax4.plot(x, np.log(x))

plt.subplots_adjust(wspace=0.4,hspace=.4)
plt.show()

Python matplotlib 画两条线 matplotlib画两个图_matplotlib_03


加入sharey,所有子图的y轴区间相同:

Python matplotlib 画两条线 matplotlib画两个图_subplor_04

subplot 与 add_subplot 很相似

x = np.arange(0, 100)
plt.subplot(221)
plt.plot(x, x)
plt.subplot(222)
plt.plot(x, -x)
plt.subplot(223)
plt.plot(x, x ** 2)
plt.subplot(224)
plt.plot(x, np.log(x))
plt.show()

Python matplotlib 画两条线 matplotlib画两个图_subplor_05