有没有办法在同一个代码中多次调用matplotlib.animation.FuncAnimation?我有一个numpy数组列表。每个数组包含不同数量的坐标。我想遍历列表并动画绘制每个数组中的点。
我能做些什么来实现这两种不同的场景: 1.保留上一个动画的最后一帧并开始一个新的动画。 2.摆脱上一个动画的最后一帧,然后重新开始 动画,但在代码的开头保持相同的布局(包括背景图)。
当我尝试在下面的for循环中使用FuncAnimation时,只有第一个数组被动画化。在每个数组之间,我还需要做一些其他的事情,所以我不能只是摆脱for循环并将数组合并为一起动画。
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
mylines = [np.array([[1,2], [3,4]]), np.array([[5,6], [7,8], [9,10]])]
fig, ax = plt.subplots()
ax.set_xlim([-10, 10])
ax.set_ylim([-10, 10])
# There's some code here to set the layout (some background plots etc)
# I omitted it in this question
def update_plot(i, data, myplot):
myplot.set_data(data[:i, 0], data[:i, 1])
return myplot,
myplot, = ax.plot([], [], '.', markersize=5)
for k in xrange(len(mylines)):
data = mylines[k]
numframes = data.shape[0]+1
delay = 500
ani = animation.FuncAnimation(fig, update_plot, frames=numframes,
fargs=(data, myplot), interval=delay,
blit=True, repeat=False)
plt.show()
# Do some more stuff in the for loop here, that's not related to
# animations but related to the current array
# Then I want to retain the last frame from the animation, and start a new
# animation on top of it. Also, what should I do if I want to erase the
# last frame instead (erase only the points plotted by the FuncAnimation,
# but keep the layout I set at the beginning)
*编辑代码,因为它有一些语法错误
ani = []
for k in xrange(len(mylines)):
data = mylines[k]
numframes = data.shape[0]+1
delay = 100
ani.append(animation.FuncAnimation(fig, update_plot, frames=numframes,
fargs=(data, myplot), interval=delay,
blit=True, repeat=False))
plt.show()
但它会同时绘制所有数组,并有一些奇怪的闪烁。
答案 0 :(得分:0)
将FuncAnimation
视为计时器。它将使用给定的参数以给定的速率调用提供给它的函数。您可以使用调用的函数来管理动画流,而不是让两个计时器在每个计时器开始和结束时都需要管理。
例如,您可以设置动画期间应该发生某事的帧号:
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
mylines = [np.array([[1,2], [3,4]]), np.array([[5,6], [7,8], [9,10]])]
fig, ax = plt.subplots()
ax.set_xlim([-10, 10])
ax.set_ylim([-10, 10])
# There's some code here to set the layout (some background plots etc)
# I omitted it in this question
myplot, = ax.plot([], [], '.', markersize=5)
delay = 500
breaking = 1
def update_plot(i, data, myplot):
myplot.set_data(data[:i, 0], data[:i, 1])
if i == breaking:
# do some other stuff
print("breaking")
myplot.set_color("red")
return myplot,
data = np.append(mylines[0],mylines[1], axis=0)
ani = animation.FuncAnimation(fig, update_plot, frames=data.shape[0],
fargs=(data, myplot), interval=delay,
blit=True, repeat=False)
plt.show()
当然这可能是任意复杂的。例如,请参阅此问题:Managing dynamic plotting in matplotlib Animation module,其中动画的方向在用户输入上反转。但是,它仍使用一个FuncAnimation
。