Python 在循环中打印(使用basemap和pyplot)…pyplot.clf()存在问题

Python 在循环中打印(使用basemap和pyplot)…pyplot.clf()存在问题,python,matplotlib,Python,Matplotlib,我正在为一个研究项目绘制一些天气数据。该图由18个时间步组成。我决定最好的方法是为每个时间步创建一个新的绘图,保存一个文件,然后为下一个时间步创建一个新的绘图(使用for循环) 例如: map_init #[Basemap Instance] extra_shapes #[Basemap.readshapefile object] for i in range(timesteps): #plot the weather data for current timestep to c

我正在为一个研究项目绘制一些天气数据。该图由18个时间步组成。我决定最好的方法是为每个时间步创建一个新的绘图,保存一个文件,然后为下一个时间步创建一个新的绘图(使用for循环)

例如:


map_init  #[Basemap Instance]
extra_shapes  #[Basemap.readshapefile object]

for i in range(timesteps):
    #plot the weather data for current timestep to current plot
    map_init.imshow(data[i])

    # extra_shapes are county boundaries.  Plot those as polygons
    pyplot.Polygon(map_init.extra_shapes[i])

    # Plot the state boundaries (in basemap)
    map_init.drawstates()

    # add a colorbar
    pyplot.colorbar()

    # Save the figure
    pyplot.savefig(filepath)

    #close figure and loop again (if necessary)
    pyplot.clf()
问题在于
pyplot.clf()

除了一件事,代码是有效的。只有第一个情节如预期的那样出现。每个后续的绘图都缺少额外的形状(即没有县边界)。我不明白
pyplot.clf()
的存在与
pyplot.Polygon()的失败之间的关系


如果删除,
extra_形状
将被打印,但每个打印都有多个色条(取决于
i
的值)。
pyplot.clf()
的唯一原因是避免在最终绘图中使用18个色条。有没有办法强制每个绘图只有一个色条?

尝试制作一个新图形,而不是使用clf()

e、 g

或者(更快)您可以只更新图像对象中的数据 (由imshow()返回)

e、 g.类似(完全未经测试):

然而,这种方法可能无法很好地处理basemap。我可能还错误地记住了重新绘制图形的正确方法,但我相当肯定这只是plt.draw()

希望这能有所帮助


编辑:刚刚注意到您正在循环内绘制多边形。更新了第二个示例以正确反映这一点。

非常感谢您的帮助。我无法使我的原始循环按预期工作(即使使用第一个示例中的建议)。然而,第二个例子很有魅力。它实际上比我原来的循环更有意义。img数据实际上是每个时间步之间唯一变化的东西。注:见上面编辑的问题原始循环背后的逻辑是一个相当仓促的尝试,试图对每个时间步进行完全独立的绘图。最初,map_init被分配到循环内部以及额外的_形状。extra_shapes是一个相当大的数据集(因为它包含美国和相关地区每个县的边界)。在循环的每次迭代中分配额外的_形状变得非常耗时(map_init也是如此)。所以把这两个任务移出循环,一切都破裂了。
for i in range(timesteps):
    fig = pyplot.figure()
    ...
    fig.savefig(filepath)
map_init  #[Basemap Instance]
extra_shapes  #[Basemap.readshapefile object]


#plot the weather data for current timestep to current plot
img = map_init.imshow(data[0])

# extra_shapes are county boundaries.  Plot those as polygons
plygn = pyplot.Polygon(map_init.extra_shapes[0])

# Plot the state boundaries (in basemap)
map_init.drawstates()

# add a colorbar
pyplot.colorbar()

for i in range(timestamps):
    img.set_data(data[i])
    plygn.set_xy(map_init.extra_shapes[i])
    pyplot.draw()
    pyplot.savefig(filepath)