Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python - Any reason why matplotlib animations would only work in interactive session?

If I create a file test.py with the code

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

if __name__ == '__main__':
    fig = plt.figure()
    title = fig.suptitle("Test _")

    def anim(i):
        title.set_text("Test %d" % i)
        plt.plot([0,1], [0,1])

    FuncAnimation(fig, anim)
    plt.show()

and try to run it in my command line, using python test.py, I get an empty screen with the title Test _ and without any axes.

The same is true when running with python -i test.py, but if I now enter the same code in the interactive session

>>> fig = plt.figure()
>>> title = fig.suptitle("Test _")
>>> FuncAnimation(fig, anim)
>>> plt.show()

everything just works as expected.

I have been looking at this for so long now and I don't seem to find any issues or questions that are related to this. I am using matplotlib 2.0.0 in python 3.5.2 on OS X.

Is this a (known) bug? Anyone with ideas why this might be happening or how this could be resolved?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the animation documentation: "[..] it is critical to keep a reference to the instance object."

So you need to keep the FuncAnimation instance alive by assigning it to a variable.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

if __name__ == '__main__':
    fig = plt.figure()
    title = fig.suptitle("Test _")

    def anim(i):
        title.set_text("Test %d" % i)
        plt.plot([0,1], [0,1])

    ani = FuncAnimation(fig, anim)
    plt.show()


There is an ongoing discussion about whether the Animation should be stored internally or not.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...