Why does this animation works only when it is stored in a variable

In the example found here (and repeated below) everything works perfectly well until I remove ani = from the line animation.FuncAnimation(fig, animate, interval=20, blit=True, save_count=50).
But this bit just assign the animation into a variable which is not used anymore ! It shouldn’t change the behavior ? Why does it ?

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.animation as animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x + i / 50))  # update the data.
    return line,

ani = animation.FuncAnimation(fig, animate, interval=20, blit=True, save_count=50)

plt.show()

If you don’t assign the animation to variable then python will eventually garbage collect the object that does the animating and it will cease to work. By assigning to a variable you prevent that from happening.

1 Like

This is documented in matplotlib.animation — Matplotlib 3.8.3 documentation

In both cases it is critical to keep a reference to the instance object. The animation is advanced by a timer (typically from the host GUI framework) which the Animation object holds the only reference to. If you do not hold a reference to the Animation object, it (and hence the timers) will be garbage collected which will stop the animation.

1 Like