Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...