在循环中绘图(使用basemap和pyplot)....pyplot.clf()的问题

1 投票
1 回答
5002 浏览
提问于 2025-04-16 02:38

我正在为一个研究项目绘制一些天气数据。这个图表有18个时间点。我决定最好的方法是为每个时间点做一个新的图,保存到文件里,然后再为下一个时间点创建一个新的图(使用循环来实现)。

比如说:


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() 这个地方。

代码基本上是可以工作的,但有一个问题。只有第一个图的效果是我想要的。后面的每个图都缺少了 extra_shapes(也就是没有县的边界)。我不明白 pyplot.clf() 的存在和 pyplot.Polygon() 的失败之间有什么关系?

如果把 pyplot.clf() 去掉,extra_shapes 就会被绘制出来,但这样每个图就会有多个颜色条(根据 i 的值)。我加 pyplot.clf() 的唯一原因是为了避免最后的图里出现18个颜色条。有没有办法让每个图只显示一个颜色条呢?

1 个回答

3

试着创建一个新的图形,而不是使用clf()。

比如:

for i in range(timesteps):
    fig = pyplot.figure()
    ...
    fig.savefig(filepath)

另外(而且更快),你可以直接更新你图像对象里的数据(这个对象是通过imshow()返回的)。

比如,像这样(完全没有测试过):

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)

不过,这种方法可能和basemap不太兼容。我可能也记错了重新绘制图形的正确方法,但我比较确定只需要用plt.draw()就可以了……

希望这些对你有点帮助。

编辑:刚注意到你在循环里绘制多边形。更新了第二个例子,以更好地反映这一点。

撰写回答