[Matplotlib-users] animation with FuncAnimation (mpl 3.0.2)
Eric Firing
efiring at hawaii.edu
Fri Mar 22 15:41:45 EDT 2019
On 2019/03/22 9:03 AM, Alan Isaac wrote:
> I think I found a bug, and I have a question.
> Consider the code below.
>
> 1. Although frames=10, `animate` is called 11 times, twice with an
> argument of 0.
> (The `print` calls show this.) I suspect this is a bug?
It's not a bug--it's intentional and documented--but I agree it is not
what one might expect. The problem is that in general animations
require an initialization followed by generation of the frames. If no
"init_func" argument is supplied for the initialization, the
frame-generator (your animate() function) is used, leading to the double
call. Since you are doing your initialization in the body of the
script, I think you could eliminate the double call to animate(0) by
supplying a do-nothing init_func argument to FuncAnimation.
>
> 2. Why is the assignment of the FuncAnimation instance to a name
> required for the animation to work, and exactly how does this trick work?
> How could I change this example to avoid this hidden magic?
This is a basic aspect of the Python language: when the last reference
to an object is removed, the object goes away. Assigning a name to the
FuncAnimation instance keeps it alive so that it can do its work when
the blocking "plt.show()" is called.
Eric
>
> Thank you,
> Alan Isaac
>
> import random
> import matplotlib.pyplot as plt
> from matplotlib.animation import FuncAnimation
>
> fig, ax = plt.subplots()
> xs, ys = [],[]
> l1, = ax.plot(xs, ys, 'b.')
> ax.set_xlim(0,10)
> ax.set_ylim(0,10)
>
> def animate(i):
> print(i)
> xs.append(random.random()*10)
> ys.append(random.random()*10)
> l1.set_data(xs, ys)
>
> ani = FuncAnimation(fig, animate, frames=10, interval=200, repeat=False)
> plt.show()
> _______________________________________________
> Matplotlib-users mailing list
> Matplotlib-users at python.org
> https://mail.python.org/mailman/listinfo/matplotlib-users
More information about the Matplotlib-users
mailing list