首页 > 解决方案 > Python matplotlib.animation.FuncAnimation 永远不会进行第二帧迭代

问题描述

我正在尝试使用 matplotlib.animation.FuncAnimation 创建自定义动画。但是,FuncAnimation 函数似乎没有对 animate 函数进行第二次迭代。我附上了一个我在网上找到的简单示例,它应该可以工作并绘制正弦波。在我的计算机和 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

在此处输入图像描述

标签: pythonmatplotlibanimation

解决方案


根据此处的示例,您还需要传递一个init_functo 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())

这使:

在此处输入图像描述


推荐阅读