Matplotlib在绘制多子图(subplots)时,如何灵活控制每个子图的布局(包括大小、间距和位置),而不仅仅依赖于`plt.subplots()`的默认参数?

在 Matplotlib 中,可以通过多种方式灵活控制多子图的布局,包括大小、间距和位置。常用的方法包括使用 plt.subplots() 的参数调整、GridSpec 类以及手动设置子图位置。以下是详细说明和示例:

1. 使用 plt.subplots() 调整布局

plt.subplots() 提供了一些参数来控制子图的布局,例如 figsize、constrained_layout 和 gridspec_kw。

示例:

import matplotlib.pyplot as plt

# 调整子图大小和间距
fig, axs = plt.subplots(2, 2, figsize=(10, 8), constrained_layout=True)
fig.suptitle('调整子图布局')

# 绘制子图
axs[0, 0].plot([1, 2, 3], label='子图1')
axs[0, 1].scatter([1, 2, 3], [3, 2, 1], label='子图2')
axs[1, 0].bar(['A', 'B', 'C'], [3, 7, 2], label='子图3')
axs[1, 1].hist([1, 2, 2, 3, 3, 3], label='子图4')

plt.legend()
plt.show()

figsize 调整整个画布的大小,constrained_layout=True 会自动调整子图之间的间距。

2. 使用 GridSpec 类

GridSpec 提供了更灵活的子图布局方式,可以定义子图的行列数、宽度比例和高度比例。

示例:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

# 定义 GridSpec 布局
gs = GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[2, 1])

fig = plt.figure(figsize=(8, 6))

# 创建子图
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, :])

# 绘制子图
ax1.plot([1, 2, 3], label='子图1')
ax2.scatter([1, 2, 3], [3, 2, 1], label='子图2')
ax3.bar(['A', 'B', 'C'], [3, 7, 2], label='子图3')

plt.legend()
plt.show()

通过 width_ratios 和 height_ratios 可以分别调整子图的宽度和高度比例。

3. 手动设置子图位置

通过 fig.add_axes() 可以完全手动指定子图的位置和大小(以画布比例表示)。

示例:

import matplotlib.pyplot as plt

# 创建画布
fig = plt.figure(figsize=(8, 6))

# 手动设置子图位置
ax1 = fig.add_axes([0.1, 0.5, 0.35, 0.4])  # [left, bottom, width, height]
ax2 = fig.add_axes([0.55, 0.5, 0.35, 0.4])
ax3 = fig.add_axes([0.1, 0.1, 0.8, 0.3])

# 绘制子图
ax1.plot([1, 2, 3], label='子图1')
ax2.scatter([1, 2, 3], [3, 2, 1], label='子图2')
ax3.bar(['A', 'B', 'C'], [3, 7, 2], label='子图3')

plt.legend()
plt.show()

通过 [left, bottom, width, height] 参数可以精确控制子图的位置和大小。

4. 调整子图间距

使用 plt.subplots_adjust() 可以调整子图之间的间距,例如 left、right、top、bottom、wspace(水平间距)和 hspace(垂直间距)。

示例:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, figsize=(8, 6))
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, wspace=0.4, hspace=0.4)

axs[0, 0].plot([1, 2, 3], label='子图1')
axs[0, 1].scatter([1, 2, 3], [3, 2, 1], label='子图2')
axs[1, 0].bar(['A', 'B', 'C'], [3, 7, 2], label='子图3')
axs[1, 1].hist([1, 2, 2, 3, 3, 3], label='子图4')

plt.legend()
plt.show()

通过调整 wspace 和 hspace 可以控制子图之间的水平间距和垂直间距。

总结:

  • 使用 plt.subplots() 的 constrained_layout 或 gridspec_kw 参数快速调整布局。
  • 使用 GridSpec 实现更复杂的行高和列宽比例。
  • 通过 fig.add_axes() 完全自定义子图位置和大小。
  • 通过 plt.subplots_adjust() 调整子图间距。