动画结束时关闭图形
原则上,您可以在循环内创建一个新图形。然后关闭一个图形将允许程序继续并创建下一个图形并显示它。动画结束时图形可以自动关闭。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def createanimatedfig(omega):
fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
ax.set_title(u"animated sin(${:g}\cdot t$)".format(omega))
t = np.linspace(0,2*np.pi)
x = np.sin(omega*t)
line, = ax.plot([],[], lw=3)
ani = FuncAnimation(fig,animate, len(t), repeat=False,
fargs=(t,x,line, len(t)), interval=20)
plt.show()
def animate(i, t,x, line, maxsteps):
line.set_data(t[:i],x[:i])
if i >= maxsteps-1:
plt.close(line.axes.figure)
omegas= [1,2,4,5]
for omega in omegas:
createanimatedfig(omega)
请注意,当使用TkAgg 后端运行时,上述内容会产生错误。在这种情况下,您需要将图形关闭推迟到动画真正停止之后。为此,可以使用计时器。
def animate(i, t,x, line, maxsteps):
line.set_data(t[:i],x[:i])
if i >= maxsteps-1:
timer = line.axes.figure.canvas.new_timer(interval=10)
timer.single_shot = True
timer.add_callback(lambda : plt.close(line.axes.figure))
timer.start()
在单个图形中运行动画
或者,您可以使用单个图形一个接一个地显示所有动画。这需要对何时停止动画进行一些控制,因此使用类来处理这些步骤很有用。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class Ani():
def __init__(self,omegas, nsteps, line):
self.nsteps = nsteps
self.omegas = omegas
self.line=line
self.step = 0
self.i = 0
def getdata(self,j):
t = np.arange(0,j)/float(self.nsteps)*2*np.pi
x = np.sin(self.omegas[self.step]*t)
return t,x
def gen(self):
for i in range(len(self.omegas)):
tit = u"animated sin(${:g}\cdot t$)".format(self.omegas[self.step])
self.line.axes.set_title(tit)
for j in range(self.nsteps):
yield j
self.step += 1
def animate(self,j):
x,y = self.getdata(j)
self.line.set_data(x,y)
fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
title = ax.set_title(u"")
line, = ax.plot([],[], lw=3)
omegas= [1,2,4,5]
a = Ani(omegas,50,line)
ani = FuncAnimation(fig,a.animate, a.gen, repeat=False, interval=60)
plt.show()