Python matplotlib.animation.FuncAnimation永远不会进行第二帧迭代

时间:2019-09-26 22:55:19

标签: python matplotlib animation

我正在尝试使用matplotlib.animation.FuncAnimation创建自定义动画。但是,FuncAnimation函数似乎并未对动画函数进行第二次迭代。我附上了一个我在网上找到的简单示例,该示例可以正常工作并绘制正弦波。在我的计算机和Amazon EC2服务器上,脚本均调用animate并绘制框架以进行一次迭代。第二次迭代似乎从未发生。我怎么了?

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)


# animation function.  This is called sequentially
def animate(i):
    print("animate invoked")
    print(i)
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=np.arange(100), interval=200)

plt.show()

脚本输出:

激活动画

0

enter image description here

1 个答案:

答案 0 :(得分:1)

根据示例here,您还需要将init_func传递给FunctionAnimation。因此,您可以这样做:

# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# init function
def init():
    return line,

# animation function.  This is called sequentially
def animate(i):
    print("animate invoked")
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = FuncAnimation(fig, animate, init_func=init, frames=np.arange(100), interval=200)

# for jupyter notebook
HTML(anim.to_html5_video())

哪个给:

enter image description here