You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在同一窗口绘制多幅等高线图:如何遍历subplots子图?

子图遍历实现方法

你调用plt.subplots(4, 2, constrained_layout=True)会返回两个对象:画布对象fig、形状为(4,2)的子图数组axs,有两种常用的遍历方式:

1. 压平数组遍历(推荐,无需区分行列)

直接将二维子图数组转为一维后和你的数据集配对遍历,适合不需要根据行列位置做特殊配置的场景:

import matplotlib.pyplot as plt
import numpy as np

# 你的初始化代码
fig, axs = plt.subplots(4, 2, constrained_layout=True)
# 替换为你自己的8份等高线源数据
datasets = [np.random.randn(50, 50) for _ in range(8)]

# 遍历配对的子图和数据
for ax, data in zip(axs.flatten(), datasets):
    # 绘制等高线,可替换为contourf绘制填充等高线
    contour = ax.contour(data)
    # 可选:添加等高线数值标签
    ax.clabel(contour, inline=True, fontsize=8)
    # 可选:添加子图标题
    ax.set_title(f"Contour Plot {datasets.index(data)+1}")

# 可选:如果数据量少于子图数量,隐藏多余子图
# for ax in axs.flatten()[len(datasets):]:
#     ax.set_visible(False)

plt.show()

2. 嵌套循环遍历

适合需要根据行、列索引做不同配置的场景:

fig, axs = plt.subplots(4, 2, constrained_layout=True)
# 假设你的数据存在二维列表datasets[row][col]中
for row in range(4):
    for col in range(2):
        current_ax = axs[row][col]
        # 替换为对应位置的实际数据
        current_data = np.random.randn(50, 50)
        current_ax.contourf(current_data, cmap="viridis")
        current_ax.set_title(f"Row {row+1}, Col {col+1}")
plt.show()
其他多等高线图绘制方案
  • 动态逐个创建子图:不需要提前批量生成所有子图,适合子图数量不固定的场景,用add_subplot实现:
fig = plt.figure(constrained_layout=True)
total_plot = 8
for idx in range(total_plot):
    ax = fig.add_subplot(4, 2, idx+1)
    ax.contour(np.random.randn(50,50))
  • 结构化数据快速绘图:如果你的等高线数据是结构化的Pandas DataFrame格式,可以用Seaborn的FacetGrid接口,无需手动遍历子图,自动按类别分组绘制等高线。
  • 统一色阶方案:如果所有子图需要共享同一个颜色刻度,绘制时统一指定vmin和vmax参数,最后在画布边缘添加全局colorbar即可,无需每个子图单独配置色条。

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:30:03