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屋!