我是basemap和python的新手,但我正在尝试为日常cron作业构建天气模型绘图仪。我们每天拍摄大约1000张照片。
我写了一些脚本来实现我想要的东西。但它花了很长时间,因为它重新绘制了每个时间步的底图。绘制底图花了30秒,只用了4秒钟绘制了contourf()。
我有一些想法通过预先绘制底图并在每次迭代中更新contourf()来加快这个过程。但我不明白matplotlib对象是如何工作的。
我已经研究了同样的问题,但没有发现任何问题。但是我从user3982706找到了here类似的东西。
from matplotlib import animation
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
fig, ax = plt.subplots()
# set up map projection
m = Basemap(projection='nsper',lon_0=-0,lat_0=90)
m.drawcoastlines()
m.drawparallels(np.arange(0.,180.,30.))
m.drawmeridians(np.arange(0.,360.,60.))
# some 2D geo arrays to plot (time,lat,lon)
data = np.random.random_sample((20,90,360))
lat = np.arange(len(data[0,:,0]))
lon = np.arange(len(data[0,0,:]))
lons,lats = np.meshgrid(lon,lat)
# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are animating three artists, the contour and 2
# annotatons (title), in each frame
ims = []
for i in range(len(data[:,0,0])):
im = m.contourf(lons,lats,data[i,:,:],latlon=True)
add_arts = im.collections
text = 'title={0!r}'.format(i)
te = ax.text(90, 90, text)
an = ax.annotate(text, xy=(0.45, 1.05), xycoords='axes fraction')
ims.append(add_arts + [te,an])
ani = animation.ArtistAnimation(fig, ims)
## If you have ffmpeg you can save the animation by uncommenting
## the following 2 lines
# FFwriter = animation.FFMpegWriter()
# ani.save('basic_animation.mp4', writer = FFwriter)
plt.show()
该脚本将轮廓数据保存为艺术家列表。我不需要动画。所以我需要编辑这个脚本来保存循环中的图形。所以这个脚本产生了figure1.png,figure2.png,figure3.png等等。
有什么建议吗?
答案 0 :(得分:0)
由于您已在代码中显示动画,因此您可以通过ani.save
命令直接保存动画的每个图像。
ani.save("figure.png", writer="imagemagick")
这将创建20个数字figure-0.png
到figure-19.png
。它需要在您的环境中安装和使用imagemagick。
如果上述因任何原因失败,您可以通过plt.savefig()
保存个人数字。在每个循环步骤结束时,您将从轴中删除艺术家并删除它们。
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
fig, ax = plt.subplots()
m = Basemap(projection='nsper',lon_0=-0,lat_0=90)
m.drawcoastlines()
m.drawparallels(np.arange(0.,180.,30.))
m.drawmeridians(np.arange(0.,360.,60.))
data = np.random.random_sample((20,90,360))
lat = np.arange(len(data[0,:,0]))
lon = np.arange(len(data[0,0,:]))
lons,lats = np.meshgrid(lon,lat)
for i in range(len(data[:,0,0])):
im = m.contourf(lons,lats,data[i,:,:],latlon=True)
text = 'title={0!r}'.format(i)
te = ax.text(90, 90, text)
an = ax.annotate(text, xy=(0.45, 1.05), xycoords='axes fraction')
# save the figure
plt.savefig("figure_{}.png".format(i))
# remove stuff from axes
for c in im.collections:
c.remove()
te.remove()
an.remove()
del im; del te; del an
plt.show()