Any reason why matplotlib animations would only wo

2020-01-29 21:56发布

问题:

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?

回答1:

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.