【问题标题】:How can I make an animation with contourf()?如何使用 contourf() 制作动画?
【发布时间】:2014-05-29 00:22:43
【问题描述】:

我正在尝试为一些时间相关数据的空间坐标的 wigner 函数设置动画。 wigner 函数是二维的,所以我使用 contourf() 来绘制它。我将数据存储在 HDF5 文件中,并且可以即时制作 Wigner 分布,但我不知道如何对其进行动画处理。我能找到的所有动画教程和示例(例如this onethis one)都是针对线图的。具体来说,他们的animate(i) 函数使用line.set_data(),我似乎找不到contourf() 的等价物。

如何为使用contourf() 制作的图像制作动画?

contourf() 相当于 set_data() 是什么?

【问题讨论】:

标签: python animation matplotlib contourf


【解决方案1】:

FuncAnimation 有一个简单的方法: 您必须具有清除轴并根据帧号绘制新轮廓的功能。不要忘记将blit 设置为False

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

DATA = np.random.randn(800).reshape(10,10,8)


fig,ax = plt.subplots()

def animate(i):
       ax.clear()
       ax.contourf(DATA[:,:,i])
       ax.set_title('%03d'%(i)) 

interval = 2#in seconds     
ani = animation.FuncAnimation(fig,animate,5,interval=interval*1e+3,blit=False)

plt.show()

【讨论】:

  • 有效,但清除和重新绘制等高线图非常慢。
【解决方案2】:

我正在绘制地理数据,因此需要底图。 基于 captain_M 的回答和https://github.com/matplotlib/matplotlib/issues/6139 上的讨论/错误报告 我发布了一个受 tacaswell 启发的响应,它允许您在二维数据动画中使用 contourf 并将其保存为 mp4(如果您有 ffmpeg):

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()

【讨论】:

  • 我错过了 set_visibleset_animated 错误,而这个对我有用。
【解决方案3】:

如果你和我一样,matplotlib.animation 不起作用。这是您可以尝试的其他方法。如果要不断更新颜色条和图中的其他所有内容,请在一开始使用 plt.ion() 以启用交互式绘图,并使用 plt.draw() 和 plt.clf() 的组合来不断更新绘图.这是示例代码:

import matplotlib.pyplot as plt
import numpy as np

plt.ion(); plt.figure(1);
for k in range(10):
    plt.clf(); plt.subplot(121);
    plt.contourf(np.random.randn(10,10)); plt.colorbar();
    plt.subplot(122,polar=True)
    plt.contourf(np.random.randn(10,10)); plt.colorbar();
    plt.draw();

请注意,这适用于包含不同子图和各种类型图(即极坐标或笛卡尔坐标)的图形

【讨论】:

    【解决方案4】:

    这是我用来制作二维等高线图的动画,改编自http://matplotlib.org/examples/animation/dynamic_image2.html

    import pylab as pl
    import numpy as np
    import matplotlib.animation as animation
    import types
    
    
    fig = pl.figure()
    # Some 2D arrays to plot (time,x,y)
    data = np.random.random_sample((20,10,10))
    
    # ims is a list of lists, each row is a list of artists to draw in the
    # current frame; here we are just animating one artist, the image, in
    # each frame
    ims = []
    for i in range(len(data[:,0,0])):
        t_step = int(i)
        im = pl.contourf(data[i,:,:])
    
        #################################################################
        ## Bug fix for Quad Contour set not having attribute 'set_visible'
        def setvisible(self,vis):
            for c in self.collections: c.set_visible(vis)
        im.set_visible = types.MethodType(setvisible,im)
        im.axes = pl.gca()
        im.figure=fig
        ####################################################################
    
        ims.append([im])
    
    ani = animation.ArtistAnimation(fig, ims, interval=70, blit=False,repeat_delay=1000)
    
    pl.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2015-10-18
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      相关资源
      最近更新 更多