使用以下脚本执行时,会生成一个行进正弦波的简单动画%run
Canopy 1.4.1 中的声明:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
def animator():
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.show()
animator()
但是,如果我删除最后一行,请运行脚本%run
并打电话animator()
从解释器来看,只在屏幕上绘制第一帧。为什么是这样?如何调用函数来在 Canopy 中生成动画?
奇怪的是,这个问题在 IDLE 或 IPython (PyLab) 中都不会发生,其中调用animator()
从口译员那里工作得很好。更重要的是,问题仅限于交互式显示:如果我再添加几行animator
要以 mp4 格式保存动画,即使从 Canopy 也能正确保存 mp4 文件。
上面的代码基于以下教程杰克·范德普拉斯.