DAT
DAT

Reputation: 3

Python matplotlib.animation.FuncAnimation never makes a second frame iteration

I am trying to use matplotlib.animation.FuncAnimation to create a custom animation. However, the FuncAnimation function does not seem to make a second iteration of the animate function. I have enclosed a simple example that I found online, which is supposed to work and draw a sine wave. Both on my computer and the Amazon EC2 server the script calls animate and draws the frame for one iteration. A second iteration never seems to happen. What am I getting wrong?

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)


# animation function.  This is called sequentially
def animate(i):
    print("animate invoked")
    print(i)
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=np.arange(100), interval=200)

plt.show()

Script output:

animate invoked

0

enter image description here

Upvotes: 0

Views: 1571

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150755

According to the example here, you need to pass an init_func to FunctionAnimation as well. So you can do:

# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# init function
def init():
    return line,

# animation function.  This is called sequentially
def animate(i):
    print("animate invoked")
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = FuncAnimation(fig, animate, init_func=init, frames=np.arange(100), interval=200)

# for jupyter notebook
HTML(anim.to_html5_video())

Which gives:

enter image description here

Upvotes: 1

Related Questions