Matplotlib - 多图
Matplotlib - 创建多个图表 (子图)
Section titled “Matplotlib - 创建多个图表 (子图)”通常,您需要在同一个图形画布 (figure canvas) 内同时显示多个图表。Matplotlib 提供了几种实现方式,允许您创建图表网格或将图表放置在自定义位置。
1. 使用 plt.subplots() (推荐)
Section titled “1. 使用 plt.subplots() (推荐)”这是创建规则子图网格最便捷和推荐的函数。它在一个函数调用中同时创建了 Figure 对象(图)和 Axes 对象(坐标轴)的 NumPy 数组。
plt.subplots(nrows=1, ncols=1, ...)nrows 和 ncols 参数定义了网格的尺寸。该函数返回一个元组:(figure, axes)。axes 要么是一个单独的 Axes 对象 (对于 1x1 的网格),要么是一个 Axes 对象的 NumPy 数组。
示例:2x2 网格
Section titled “示例:2x2 网格”import matplotlib.pyplot as pltimport numpy as np
# 创建一个图和2x2网格的坐标轴对象fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8), layout='constrained')
# 绘图数据x = np.linspace(0, 2 * np.pi, 100)
# 使用数组索引访问单个坐标轴axes[0, 0].plot(x, np.sin(x), 'r-')axes[0, 0].set_title('Top Left (Sine)')
axes[0, 1].plot(x, np.cos(x), 'g--')axes[0, 1].set_title('Top Right (Cosine)')
axes[1, 0].plot(x, np.tan(x), 'b.')axes[1, 0].set_title('Bottom Left (Tangent)')axes[1, 0].set_ylim(-5, 5) # 限制y轴范围以适应tan函数
axes[1, 1].plot(x, np.exp(-x), 'k:')axes[1, 1].set_title('Bottom Right (Exponential Decay)')
# 为整个图添加主标题fig.suptitle('Example 2x2 Subplots', fontsize=16)
# 自动调整布局 (plt.subplots 中 layout='constrained' 的替代方案)# plt.tight_layout(rect=[0, 0, 1, 0.96]) # rect 用于为 suptitle 留出空间
plt.show()这段代码创建了一个包含四张图的 Figure,它们排列在一个 2x2 的网格中。每张图都是通过调用 axes 数组中对应 Axes 对象的方法来创建的。
2. 使用 fig.add_subplot()
Section titled “2. 使用 fig.add_subplot()”这个方法是面向对象 API 的一部分,用于向一个已有的 Figure (fig) 中添加一个单独的子图。您需要指定网格的几何形状以及要创建的子图的索引。
fig = plt.figure()ax1 = fig.add_subplot(nrows, ncols, index)# 索引从1到 nrows * ncols,按行递增缩写表示法 fig.add_subplot(221) 等价于 fig.add_subplot(2, 2, 1)。
示例:重叠的子图 (不太常用)
Section titled “示例:重叠的子图 (不太常用)”虽然 plt.subplots 很好地管理了非重叠的图,但 add_subplot 在技术上可以通过传入冲突的索引来创建重叠的图,尽管这通常不是期望的结果。
fig = plt.figure(figsize=(6, 4))
# 添加第一个子图(覆盖整个图区域)ax1 = fig.add_subplot(1, 1, 1)ax1.plot([1, 2, 3], [1, 2, 3], 'r-')ax1.set_title('Axes 1 (Full)')
# 添加第二个子图(左上象限),可能与 ax1 内容重叠ax2 = fig.add_subplot(2, 2, 1, facecolor='lightblue') # 2x2 网格,第1个图ax2.plot([1, 2, 3], [3, 2, 1], 'b--')ax2.set_title('Axes 2 (Top-Left)')
plt.show()这个例子展示了 add_subplot 如何单独添加 Axes。小心地使用它可以创建用简单网格无法实现的复杂布局。
3. 使用 fig.add_axes() 进行自定义位置放置 (内嵌图)
Section titled “3. 使用 fig.add_axes() 进行自定义位置放置 (内嵌图)”如果您需要完全控制子图的位置和大小,请使用 fig.add_axes([left, bottom, width, height])。坐标是 Figure 尺寸的分数比例。
示例:带内嵌图的图表
Section titled “示例:带内嵌图的图表”import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 2 * np.pi, 200)
fig = plt.figure(figsize=(8, 5))
# 主坐标轴ax_main = fig.add_axes([0.1, 0.1, 0.8, 0.8])ax_main.plot(x, np.sin(x), 'b-')ax_main.set_title('Main Plot (Sine)')ax_main.set_xlabel('X')ax_main.set_ylabel('sin(x)')
# 内嵌坐标轴ax_inset = fig.add_axes([0.6, 0.6, 0.25, 0.25]) # 位置:[left, bottom, width, height]ax_inset.plot(x, np.cos(x), 'r--')ax_inset.set_title('Inset Plot (Cosine)')ax_inset.set_xticks([]) # 如果需要,隐藏内嵌图的刻度ax_inset.set_yticks([])
plt.show()这段代码创建了一个主图,显示正弦波,并在主图的右上角区域放置了一个较小的内嵌图,显示余弦波。add_axes 非常适合这种自定义布局。
选择最适合您布局需求的方法:plt.subplots() 用于规则网格,fig.add_subplot() 用于可能需要逐步构建的复杂基于网格的布局,而 fig.add_axes() 用于精确、任意的位置放置。