Using matplotlib.animation inside a function in Canopy [duplicate]

寵の児 提交于 2019-12-01 12:21:05

问题


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:


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!



来源:https://stackoverflow.com/questions/25537734/using-matplotlib-animation-inside-a-function-in-canopy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!