在循环中保存 pcolormesh 时出现问题

问题描述 投票:0回答:1

我正在尝试使用以下代码在循环中保存许多包含 matplotlib pcolormesh 的图像:

import matplotlib.pyplot as plt
import numpy as np

time_axis = np.arange(0, 30 + 1 / 50, 1 / 50)
another_axis = np.arange(0, 10, 1)

grid = np.zeros((len(another_axis), len(time_axis)))
fig, ax = plt.subplots()

for i in range(2):
    grid = np.random.random((len(another_axis), len(time_axis)))
    pcm = ax.pcolormesh(time_axis, another_axis, grid)
    fig.colorbar(pcm, ax=ax)
    fig.savefig(f"test{i}.png")
    plt.clf()

但是我的第二个图总是看起来像所附的(第二张)图像。我无法判断这是否是 pcolormesh 或 colorbar 等的问题。也许是 plt.clf() 的问题?我正在使用它,我认为它与这个答案中的想法一致。

编辑:尝试在最后使用

ax.clear()
意味着第二个图有两个颜色条。

test1.png2 test2.png1

python matplotlib
1个回答
0
投票

您遇到的问题是,当您调用

plt.clf()
时,它会从图中删除所有内容,包括 Axes 实例
ax
。因此,当您在下一次迭代中使用
ax.pcolormesh
时,即尝试将 pcolormesh 放置在不再显示在此图上的 Axes 实例上。

一种解决方案是每次在循环中重新创建

ax
。您可以使用
ax = fig.add_subplot()
来完成此操作,但是当您创建图形时,我们不想同时创建
ax
,因此我们会将其从
plt.subplots() 
更改为
plt.figure()
:

fig = plt.figure()

for i in range(2):
    ax = fig.add_subplot()
    grid = np.random.random((len(another_axis), len(time_axis)))
    pcm = ax.pcolormesh(time_axis, another_axis, grid)
    fig.colorbar(pcm, ax=ax)
    fig.savefig(f"test{i}.png")
    fig.clf()
© www.soinside.com 2019 - 2024. All rights reserved.