Matplotlib 子图(Subplots)解析

Matplotlib 子图(Subplots)解析

子图(Subplots)可以帮助我们在 同一个画布(figure) 上绘制多个不同的图表,方便进行 数据对比展示多个视角 的数据。


1. 什么是 figuresubplot

  • figure:整个 画布(canvas),包含一个或多个子图。
  • subplot:画布上的 单个子图,可以包含不同类型的图表。

在 Matplotlib 中,我们可以使用 plt.subplots() 来创建多个子图:

1
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))
  • nrows=1, ncols=2:表示 创建 1 行 2 列的子图(即两个并排的图)。
  • figsize=(12, 6):设置 整体画布大小

2. 子图示例

我们以 中国(China)和印度(India)的移民数据 为例,绘制:

  1. 箱线图(Boxplot)
  2. 折线图(Line plot)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import matplotlib.pyplot as plt

# 创建画布,1 行 2 列的子图
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))

# 绘制箱线图(左侧子图)
df[['China', 'India']].plot(kind='box', ax=axes[0], color='blue')
axes[0].set_title('Box plot of China & India Immigration')

# 绘制折线图(右侧子图)
df[['China', 'India']].plot(kind='line', ax=axes[1])
axes[1].set_title('Line plot of China & India Immigration')

# 调整布局,使图表不重叠
plt.tight_layout()

# 显示图表
plt.show()

3. 代码解析

(1) 创建 1 行 2 列的子图

1
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))
  • nrows=1, ncols=2:创建 一行两列 的子图布局。
  • figsize=(12, 6):设置 画布大小

(2) 绘制箱线图

1
2
df[['China', 'India']].plot(kind='box', ax=axes[0], color='blue')
axes[0].set_title('Box plot of China & India Immigration')
  • ax=axes[0]:指定绘制到 第 1 个子图(左侧)
  • set_title():设置 子图标题

(3) 绘制折线图

1
2
df[['China', 'India']].plot(kind='line', ax=axes[1])
axes[1].set_title('Line plot of China & India Immigration')
  • ax=axes[1]:指定绘制到 第 2 个子图(右侧)

(4) 调整布局

1
plt.tight_layout()
  • 这个函数 自动调整子图的间距,避免重叠。

(5) 显示图表

1
plt.show()

4. 结果

左侧子图(箱线图):显示中国和印度移民数量的分布情况。
右侧子图(折线图):显示移民数量的变化趋势。
整体布局清晰、易读,适用于数据对比


5. 其他子图布局

除了 1x2 的布局,我们还可以使用其他布局:

(1) 2x2 子图

1
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))

这将创建一个 2 行 2 列的网格布局,适合显示 4 个图。

(2) 不规则布局(GridSpec)

如果想要 不同大小的子图,可以用 GridSpec

1
2
3
4
5
6
7
8
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(10, 8))
gs = gridspec.GridSpec(2, 2, height_ratios=[2, 1])

ax1 = plt.subplot(gs[0, :]) # 第 1 行,占满 2 列
ax2 = plt.subplot(gs[1, 0]) # 第 2 行,左侧
ax3 = plt.subplot(gs[1, 1]) # 第 2 行,右侧
  • 上方大图,下方两张小图

总结

  • plt.subplots() 可以创建多个子图,便于 数据对比
  • ax=axes[i] 指定不同的子图位置。
  • plt.tight_layout() 避免子图重叠。
  • GridSpec 适用于 不规则子图布局

这样,我们可以 高效可视化 数据! 🎉

作者

Ethan Wilkins

发布于

2025-03-12

更新于

2025-03-12

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.