如何创建包含多个子图的Figure?

中等机器学习

答题要点

import matplotlib.pyplot as plt
import numpy as np

# 方法1:subplots创建规则网格
fig, axes = plt.subplots(2, 2, figsize=(10, 8))  # 2行2列
axes[0, 0].plot([1, 2, 3], [1, 2, 3])
axes[0, 0].set_title('子图1')
axes[0, 1].scatter([1, 2, 3], [3, 2, 1])
axes[0, 1].set_title('子图2')
axes[1, 0].bar(['A', 'B', 'C'], [10, 20, 15])
axes[1, 0].set_title('子图3')
axes[1, 1].hist(np.random.randn(1000), bins=30)
axes[1, 1].set_title('子图4')
plt.tight_layout()  # 自动调整间距避免重叠
plt.show()

# 一行或一列子图
fig, axes = plt.subplots(1, 3, figsize=(15, 5))  # 1行3列
for i, ax in enumerate(axes):
    ax.plot(np.random.randn(100))
    ax.set_title(f'子图{i+1}')
plt.show()

# 共享坐标轴
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
# 所有子图共享X轴和Y轴范围

# 方法2:subplot创建单个子图(旧式)
plt.subplot(2, 2, 1)  # 2行2列的第1个
plt.plot([1, 2, 3])
plt.subplot(2, 2, 2)  # 第2个
plt.scatter([1, 2, 3], [3, 2, 1])

# 方法3:GridSpec复杂布局
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(10, 8))
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :])  # 第一行全部
ax2 = fig.add_subplot(gs[1, :-1])  # 第二行前2列
ax3 = fig.add_subplot(gs[1:, -1])  # 第二三行最后一列
ax4 = fig.add_subplot(gs[-1, 0])  # 左下角
ax5 = fig.add_subplot(gs[-1, -2])  # 右下角第二个

# 方法4:subplot2grid不规则布局
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)  # 第一行3列
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)  # 第二行前2列
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)  # 第二三行最后列

# 调整子图间距
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1,
                    hspace=0.3, wspace=0.3)

# 删除子图
fig, axes = plt.subplots(2, 2)
fig.delaxes(axes[1, 1])  # 删除右下角子图

# 全局标题
fig.suptitle('整体标题', fontsize=16)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题