J_yang
J_yang

Reputation: 2822

Matplotlib animation duration and why it won't stop

matplotlib animation duration explained that basically the argument franes in FuncAnimation defines the total amount of frames it should animate. However, when I run the example code it just seems to be running constantly. I expected the fig will stop updating after 4 seconds but it didnot. Is there some kind of loop I need to disable? Thanks. I ran it on Python 3.7 and matplotlib 3.0.3

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

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2,2))
line, = ax.plot([], [], lw=2)

# init func, plot the background of each frame. 
def init():
    line.set_data([], [])
    return line, 

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line, 

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
plt.show()

Upvotes: 0

Views: 1322

Answers (2)

furas
furas

Reputation: 142992

As default it repeats animation but you can use

FuncAnimation(... , repeat=False)

Doc: FuncAniamtion

Upvotes: 0

Rikka
Rikka

Reputation: 1049

You need repeat=False in your FuncAnimation call.

Checkout the doc please https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html#matplotlib.animation.FuncAnimation

repeat : bool, optional

    Controls whether the animation should repeat when the sequence of frames is completed. Defaults to True.

Upvotes: 1

Related Questions