Matplotlib 子图(Subplots)解析 子图(Subplots)可以帮助我们在 同一个画布(figure) 上绘制多个不同的图表,方便进行 数据对比 或 展示多个视角 的数据。
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)的移民数据 为例,绘制:
箱线图(Boxplot)
折线图(Line plot)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import matplotlib.pyplot as pltfig, 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) 调整布局
(5) 显示图表
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 gridspecfig = plt.figure(figsize=(10 , 8 )) gs = gridspec.GridSpec(2 , 2 , height_ratios=[2 , 1 ]) ax1 = plt.subplot(gs[0 , :]) ax2 = plt.subplot(gs[1 , 0 ]) ax3 = plt.subplot(gs[1 , 1 ])
总结
plt.subplots()
可以创建多个子图,便于 数据对比 。
ax=axes[i]
指定不同的子图位置。
plt.tight_layout()
避免子图重叠。
GridSpec
适用于 不规则子图布局 。
这样,我们可以 高效可视化 数据! 🎉