about the args of matplotlib.animation.FuncAnimation


Question

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)        # x-array
i=1
line, = ax.plot(x, np.sin(x))

def animate():
    i= i+2
    x=x[1:] + [i]
    line.set_ydata(np.sin(x))  # update the data
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init,
    interval=25, blit=True)
plt.show()

I get error like this:animate() takes no arguments (1 given)..so confused. i don't even give an arg to the callback func. Was there something that i missed?

thanks.

1
3
11/30/2012 1:20:25 AM

Accepted Answer

It looks like the documentation is off, or at least unclear here: the function has an intrinsic first argument, the frame number. So you can simply define it as def animate(*args) or def animate(framenumber, *args), or even def animate(framenumber, *args, **kwargs).

See also this example.

Note that you'll run into other problems after that:

  • i and x within animate should be declared global. Or better, pass them as arguments through the fargs keyword in FuncAnimation.

  • x = x[1:] + [i] doesn't work the way you think it does. Numpy arrays work differently than lists: it would add [i] to every element of x[1:] and assign that to x, thus making x one element shorter. One possible correct way would be x[:-1] = x[1:]; x[-1] = i.

6
11/30/2012 10:02:11 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon