在Canopy中函数内使用matplotlib.animation

1 投票
1 回答
2747 浏览
提问于 2025-04-18 18:47

下面这个脚本在Canopy 1.4.1中用%run命令执行时,会产生一个简单的波动动画:

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文件也能正确保存。

上面的代码是基于Jake Vanderplas的教程。

1 个回答

1

我找到了我问题第二部分的答案:正如这个回答所建议的,我必须在函数中使用return anim。不过,我还是有点困惑,为什么Canopy和其他解释器在这里的表现不一样。(为什么IDLE和PyLab可以正常工作呢?)如果有人能给我一些见解,我会很感激!

撰写回答