在Canopy中的函数内使用matplotlib.animation [英] Using matplotlib.animation inside a function in Canopy
问题描述
以下脚本在Canopy 1.4.1中使用%run
语句执行时,会生成正弦波的简单动画:
The following script produces a simple animation of a traveling sine wave when executed using the %run
statement in 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中生成动画?
However, if I remove the last line, run the script with %run
and call animator()
from the interpreter, only the first frame is drawn on the screen. Why is this? How can I get a function call to produce an animation within Canopy?
奇怪的是,在IDLE或IPython(PyLab)中都不会发生此问题,在这种情况下,从解释器调用 animator()
可以正常工作.而且,问题仅限于交互式显示:如果我在 animator
中再添加几行以将动画保存为mp4格式,则即使从Canopy中也可以正确保存mp4文件.
Oddly, this problem does not occur in either IDLE or IPython (PyLab), where calling animator()
from the interpreter works fine. What is more, the issue is limited to the interactive display: if I add a few more lines to animator
to save the animation in mp4 format, the mp4 file is saved correctly even from Canopy.
以上代码基于 Jake Vanderplas 的教程.
推荐答案
我已经找到了问题第二部分的答案:如建议的在这个答案 中,我必须有return anim
函数.但是对于Canopy和其他口译人员在这里的行为方式为何有所不同,我仍然有些困惑.(为什么IDLE和PyLab起作用?)任何见识将不胜感激!
I have figured out an answer to the second part of my question: as suggested in this answer, I must have the function return anim
. But I remain somewhat confused as to why Canopy and the other interpreters behave differently here. (Why do IDLE and PyLab work?) Any insight would be appreciated!
这篇关于在Canopy中的函数内使用matplotlib.animation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!