簡體   English   中英

如何用contourf()制作動畫?

[英]How can I make an animation with contourf()?

我正在嘗試動畫一些時間相關數據的空間坐標的wigner函數。 wigner函數是2維的,所以我使用contourf()來繪制它。 我將數據存儲在HDF5文件中,可以動態制作Wigner,但我無法弄清楚如何設置動畫。 我能夠找到的所有動畫教程和示例(例如這一個這個 )都嚴格用於線圖。 具體來說,他們的animate(i)函數使用line.set_data() ,我似乎無法找到contourf()的等價物。

如何使用contourf()制作動畫圖像?

contourf()相當的set_data()什么?

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

這是我用來制作2d等高線圖的動畫,它改編自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()

我正在繪制地理數據,因此需要底圖。 基於captain_M的回答和關於https://github.com/matplotlib/matplotlib/issues/6139的討論/錯誤報告,我發布了一個受tacaswell啟發的響應 ,允許您在二維數據動畫中使用contourf並保存如果你有ffmpeg它作為mp4:

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

如果你像我一樣,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();

請注意,這適用於包含不同子圖和各種類型圖(即極地或笛卡兒)的圖形

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM