python - 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
解决方案
根据此处的示例,您还需要传递一个init_func
to 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())
这使:
推荐阅读
- c++ - 对象内部对象的重载函数
- python - 如何合并熊猫数据框中的两列,堆叠在顶部
- c# - 如何使用密码保护文件夹中的多个压缩文件进行压缩?
- python - 用python读取pdf中的两侧表
- sql - 需要 SQL 来选择行,直到列的总和达到最后一行不会完全消耗值的值
- nativescript - 在 Android 上获取 Mac 地址
- sql - 如何在函数中抛出异常
- google-app-maker - 检查以逗号分隔的字符串以获取绑定中的值
- regex - 正则表达式匹配字符串,中间有一个可选部分,中间用空格括起来
- jquery - 从使用ajax附加行的表中使用jquery ajax删除记录?