022540341 suxin 课程作业
第 5 章 / 共 7 章

子图的绘制及坐标轴共享

一张画布里放多张图,才能做横向对比。这一章讲怎么切分布局,以及怎么让多个子图共用一条坐标轴。

本章目录

  1. 5.1 2×2 子图:add_subplot 网格布局
  2. 5.2 共享坐标轴:sharex / sharey
  3. 5.3 GridSpec:不等分的复杂布局
5.1

2×2 子图:add_subplot 网格布局

add_subplot(行, 列, 序号) 把画布切成网格,序号从 1 开始、按行从左到右编号。

2×2 子图:add_subplot 网格布局

四种不同的图形放在同一个 2×2 网格里,fig.suptitle 给整张画布加总标题。

python
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
fig = plt.figure(figsize=(7.8, 5.6))
axes = [fig.add_subplot(2, 2, i + 1) for i in range(4)]

axes[0].plot([1, 2, 3, 4, 5], [3, 5, 4, 7, 6])
axes[0].set_title('折线图')
axes[1].bar(['A', 'B', 'C'], [4, 7, 5])
axes[1].set_title('柱形图')
axes[2].scatter(np.random.rand(30), np.random.rand(30), s=18)
axes[2].set_title('散点图')
axes[3].hist(np.random.normal(0, 1, 200), bins=15)
axes[3].set_title('直方图')

fig.suptitle('2×2 子图布局', fontsize=13)
fig.tight_layout()
plt.show()
5.2

共享坐标轴:sharex / sharey

上下两张图如果看的是同一段时间,让它们共用 x 轴,读者就能直接对齐着读:上面看量、下面看率。

共享坐标轴:sharex / sharey

上图订单量、下图退单率,sharex=True 让两张图共用日期轴,height_ratios 控制上下高度比 2:1。

python
import numpy as np
import matplotlib.pyplot as plt

days = np.arange(1, 15)
orders = [120, 130, 125, 150, 160, 145, 170, 165,
          180, 175, 190, 185, 200, 195]
refund = [0.12, 0.11, 0.13, 0.10, 0.09, 0.11, 0.08,
          0.09, 0.07, 0.08, 0.06, 0.07, 0.05, 0.06]

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7.4, 5), sharex=True,
                               gridspec_kw={'height_ratios': [2, 1]})
ax1.plot(days, orders, marker='o', color='#2f6f5e')
ax1.set_ylabel('订单量')
ax1.set_title('共享 x 轴的上下子图')

ax2.bar(days, refund, color='#c98b3a')
ax2.set_ylabel('退单率')
ax2.set_xlabel('日期(3 月)')

fig.tight_layout()
plt.show()
5.3

GridSpec:不等分的复杂布局

当主图需要占满整行、下面两张小图并排时,add_subplot 的等分网格就不够用了,改用 GridSpec 指定每块占几行几列。

GridSpec:不等分的复杂布局

顶部主图 gs[0, :] 跨 3 列,左下 gs[1, 0] 占 1 列,右下 gs[1, 1:] 跨 2 列。

python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

x = np.linspace(0, 10, 120)
fig = plt.figure(figsize=(7.8, 5.2))
gs = gridspec.GridSpec(2, 3, height_ratios=[2, 1])

ax_a = fig.add_subplot(gs[0, :])
ax_b = fig.add_subplot(gs[1, 0])
ax_c = fig.add_subplot(gs[1, 1:])

ax_a.plot(x, np.sin(x), color='#2f6f5e')
ax_a.set_title('主图:整行展示')
ax_b.bar(['甲', '乙', '丙'], [3, 6, 4])
ax_b.set_title('并列小图 1')
ax_c.scatter(x, np.cos(x), s=9, alpha=0.6)
ax_c.set_title('并列小图 2')

fig.tight_layout()
plt.show()