CHAPTER 05 · CASE STUDIES

子图的绘制及坐标轴共享

当需要在同一张画布中呈现多个视角时,子图是最常用的手段。本章介绍规则网格 subplots()、自由布局 GridSpec 以及坐标轴共享设置,重点在于保持多图之间的尺寸协调、间距统一与刻度对齐。

案例数量3 组
核心内容subplots() · GridSpec · sharex / sharey
章节编号05

CASE STUDIES

案例分区

文字说明 / 代码展示 / 图表图片 三段式结构

CASE5.1

使用 subplots 创建规则网格

subplots(2, 2) 返回一个 Axes 数组,通过索引分别绘制四条曲线。最后统一为所有子图添加浅色网格,保证版面节奏一致。

PYTHON 示例代码
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 200)
fig, axes = plt.subplots(2, 2, figsize=(10, 7))

axes[0, 0].plot(x, np.sin(x), color='#16243A')
axes[0, 0].set_title('正弦曲线')
axes[0, 1].plot(x, np.cos(x), color='#A88450')
axes[0, 1].set_title('余弦曲线')
axes[1, 0].plot(x, np.exp(x / 4), color='#2A3F63')
axes[1, 0].set_title('指数曲线')
axes[1, 1].plot(x, np.sqrt(x), color='#6D7789')
axes[1, 1].set_title('平方根曲线')

for ax in axes.flat:
    ax.grid(alpha=0.25)

plt.tight_layout()
plt.show()
图 5-1 · 2×2 规则子图网格
图 5-1 · 2×2 规则子图网格
CASE5.2

使用 GridSpec 自定义布局

GridSpec 允许子图跨行跨列。示例中左侧主图占据两行,右侧上下各放一张辅助图,形成主次分明的仪表盘式版面。

PYTHON 示例代码
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 6))
gs = GridSpec(2, 3, figure=fig, hspace=0.3, wspace=0.3)

ax_main = fig.add_subplot(gs[:, :2])    # 跨两行的大图
ax_top = fig.add_subplot(gs[0, 2])
ax_bottom = fig.add_subplot(gs[1, 2])

ax_main.plot([1, 2, 3, 4], [6, 9, 8, 12], color='#16243A', marker='o')
ax_main.set_title('主图:趋势分析')
ax_top.bar([1, 2], [3, 5], color='#A88450')
ax_bottom.pie([6, 4], labels=['A', 'B'],
              colors=['#16243A', '#D6C5A4'])

plt.show()
图 5-2 · GridSpec 自定义子图布局
图 5-2 · GridSpec 自定义子图布局
CASE5.3

共享坐标轴与间距调整

对上下排列且使用相同量纲的子图,设置 sharex / sharey 可以隐藏重复刻度,让画布更简洁紧凑。

PYTHON 示例代码
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 8, 120)
fig, axes = plt.subplots(2, 1, figsize=(8, 7),
                         sharex=True, sharey=True)

axes[0].plot(x, np.sin(x), color='#16243A')
axes[0].set_title('共享 X / Y 坐标轴')
axes[1].plot(x, np.cos(x), color='#A88450')

# 只在下方子图保留刻度标签
plt.setp(axes[0].get_xticklabels(), visible=False)
fig.subplots_adjust(hspace=0.12)

plt.show()
图 5-3 · 共享坐标轴的子图
图 5-3 · 共享坐标轴的子图

BACK TO INDEX

返回作品集首页

浏览其他章节内容

返回首页 →