eerio
eerio

Reputation: 53

FuncAnimation() doesn't work when not assigned to a variable

I have the following snippet of Python code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)

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 / 10))
    return line,
# note: no anim=animation.FuncAnimation(...) assignment
animation.FuncAnimation(fig, animate)
plt.show()

It doesn't work as I would expect - when ran, it displays a sine plot on the graph, but it doesn't update. It does though, when FuncAnimation() result is assigned to a variable. Why is it? How can a Python object know that it has been assigned to a variable?

Upvotes: 1

Views: 1045

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339340

The documentation explains it:

[..] 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.

Upvotes: 2

Related Questions