Matplotlib FuncAnimation仅绘制一帧 [英] Matplotlib FuncAnimation only draws one frame
问题描述
我正在尝试使用FuncAnimation
模块制作动画,但是我的代码仅产生一帧,然后停止.似乎没有意识到需要更新什么.您能帮我解决问题吗?
I am trying to do an animation using the FuncAnimation
module, but my code only produces one frame and then stops. It seems like it doesn't realize what it needs to update. Can you help me what went wrong?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
def animate(i):
PLOT.set_data(x[i], np.sin(x[i]))
print("test")
return PLOT,
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
推荐答案
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
def animate(i):
PLOT.set_data(x[:i], np.sin(x[:i]))
# print("test")
return PLOT,
ani = animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
您需要保留对动画对象的引用,否则它会被垃圾收集并且计时器消失.
You need to keep a reference to the animation object around, otherwise it gets garbage collected and it's timer goes away.
存在一个未解决的问题,用于将硬引用附加到动画上基础Figure
对象.
There is an open issue to attach a hard-ref to the animation to the underlying Figure
object.
按照编写的方式,您的代码只能绘制一个不可见的点,我对其进行了一些更改以将绘制为当前索引
As written, your code well only plot a single point which won't be visible, I changed it a bit to draw up to current index
这篇关于Matplotlib FuncAnimation仅绘制一帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!