Python Matplotlib FuncAnimation只绘制一帧

thr*_*434 3 python animation matplotlib

地球人!
我正在尝试使用该FuncAnimation模块进行动画,但我的代码只生成一个帧然后停止.似乎它没有意识到他需要更新什么.你能帮我解决问题吗?

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()
Run Code Online (Sandbox Code Playgroud)

tac*_*ell 6

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()
Run Code Online (Sandbox Code Playgroud)

你需要保持对动画对象的引用,否则它会被垃圾收集而且它的计时器会消失.

一个未解决的问题是将动画的硬参考附加到底层Figure对象.

由于写的,你的代码以及只绘制一个点,这将是不可见的,我改变了它有点吸取多达当前索引