Using matplotlib.animation inside a function in Ca

2019-02-20 10:08发布

This question already has an answer here:

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()

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?

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.

The code above is based on a tutorial by Jake Vanderplas.

1条回答
冷血范
2楼-- · 2019-02-20 10:18

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!

查看更多
登录 后发表回答