使用plt.subplots()和add_subplot可在Matplotlib中创建多子图,前者适合规则布局,后者适用于灵活排版,结合tight_layout和共享坐标轴可优化显示效果。

在Python中使用Matplotlib可以在一个画布(Figure)中绘制多个图表,常用的方法是通过 subplots 或 add_subplot 来创建子图区域。下面介绍两种主要方式。
使用 plt.subplots() 创建多个子图
这是最常见且推荐的方式,可以一次性创建多个子图,并返回一个画布对象和子图数组。
import matplotlib.pyplot as plt import numpy as np生成示例数据
x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) y3 = np.tan(x) y4 = x ** 2
创建 2x2 的子图布局
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
在每个子图中绘图
axs[0, 0].plot(x, y1, color='blue') axs[0, 0].set_title('sin(x)')
axs[0, 1].plot(x, y2, color='green') axs[0, 1].set_title('cos(x)')
axs[1, 0].plot(x, y3, color='red') axs[1, 0].set_title('tan(x)')
axs[1, 1].plot(x, y4, color='purple') axs[1, 1].set_title('x²')
自动调整子图间距
plt.tight_layout() plt.show()
使用 add_subplot 手动添加子图
适用于需要更灵活控制子图位置的情况,比如非均匀布局。
立即学习“Python免费学习笔记(深入)”;
fig = plt.figure(figsize=(10, 8))添加第一个子图(第1行第2列中的第1个)
ax1 = fig.add_subplot(2, 2, 1) ax1.plot(x, y1) ax1.set_title('sin(x)')
添加第二个子图
ax2 = fig.add_subplot(2, 2, 2) ax2.plot(x, y2) ax2.set_title('cos(x)')
第三个
ax3 = fig.add_subplot(2, 2, 3) ax3.plot(x, y3) ax3.set_title('tan(x)')
第四个
ax4 = fig.add_subplot(2, 2, 4) ax4.plot(x, y4) ax4.set_title('x²')
plt.tight_layout() plt.show()
调整布局与美化
多个图表容易重叠,建议使用以下方法优化显示:
- plt.tight_layout():自动调整子图参数,防止重叠
- figsize 参数设置画布大小
- 每个子图可单独设置标题、坐标轴标签等
- 使用 sharex 或 sharey=True 共享坐标轴
基本上就这些。用 subplots 更简洁,适合规则布局;add_subplot 更灵活,适合复杂排版。根据需求选择即可。










