更新时间:2023-02-06 07:40:51
这是一个关于如何在动画中使用 contour
绘图的示例.它使用 matplotlib.animation.FuncAnimation
这使得打开和关闭 blitting 变得容易.使用 blit=True 它在我的机器上以 ~64 fps 的速度运行,而不会以 ~55 fps 的速度运行.请注意,interval
当然必须允许快速动画;将其设置为 interval=10
(毫秒)将允许高达 100 fps,但绘制时间将其限制为比这更慢的速度.
Here is an example on how to use a contour
plot in an animation. It uses matplotlib.animation.FuncAnimation
which makes it easy to turn blitting on and off.
With blit=True it runs at ~64 fps on my machine, without blitting ~55 fps. Note that the interval
must of course allow for the fast animation; setting it to interval=10
(milliseconds) would allow for up to 100 fps, but the drawing time limits it to something slower than that.
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
import time
x= np.linspace(0,3*np.pi)
X,Y = np.meshgrid(x,x)
f = lambda x,y, alpha, beta :(np.sin(X+alpha)+np.sin(Y*(1+np.sin(beta)*.4)+alpha))**2
alpha=np.linspace(0, 2*np.pi, num=34)
levels= 10
cmap=plt.cm.magma
fig, ax=plt.subplots()
props = dict(boxstyle='round', facecolor='wheat')
timelabel = ax.text(0.9,0.9, "", transform=ax.transAxes, ha="right", bbox=props)
t = np.ones(10)*time.time()
p = [ax.contour(X,Y,f(X,Y,0,0), levels, cmap=cmap ) ]
def update(i):
for tp in p[0].collections:
tp.remove()
p[0] = ax.contour(X,Y,f(X,Y,alpha[i],alpha[i]), levels, cmap= cmap)
t[1:] = t[0:-1]
t[0] = time.time()
timelabel.set_text("{:.3f} fps".format(-1./np.diff(t).mean()))
return p[0].collections+[timelabel]
ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(alpha),
interval=10, blit=True, repeat=True)
plt.show()
请注意,在上面的动画 gif 中显示了较慢的帧速率,因为保存图像的过程需要更长的时间.
Note that in the animated gif above a slower frame rate is shown, since the process of saving the images takes a little longer.