Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 57 ยท 3D, Animation and Advanced

Animation Concepts

Understand how FuncAnimation and ArtistAnimation work: update functions, frames, interval and blit, saving GIF or MP4, and previewing frames as a filmstrip.

An animation is a list of pictures shown quickly one after the other. Matplotlib does not store a movie; it keeps one figure and changes it between frames, redrawing after each change. That tiny idea explains every parameter of FuncAnimation: what to change, how many times, how fast, and how much to redraw.

On this site figures appear as still images, and there is no video writer in the browser. So we will learn the concepts with the real code (shown read-only where it needs a window or a writer) and with an equivalent technique that does run here: calling the same update function by hand and laying the frames side by side as a filmstrip. That is also the best way to debug an animation. You should know line plots and the object-oriented API.

How an animation runs

Frames A number, list or generator of values.
Update function Changes the artists for one frame.
Interval Milliseconds between frames.
Blit Redraw only what changed.

Each frame value is passed to your update function.

1 / 2

The update-function pattern

The pattern has three steps:

  1. Draw the first frame and keep references to the artists that will change (a line, a scatter, a text).
  2. Write update(frame), which modifies those artists with set_data, set_offsets, set_text and so on, and returns them.
  3. Hand both to FuncAnimation.
Python
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
(line,) = ax.plot([], [])
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.1, 1.1)

def update(frame):
    x = np.linspace(0, 2 * np.pi, 200)
    line.set_data(x, np.sin(x + frame / 10))
    return (line,)

anim = FuncAnimation(fig, update, frames=60, interval=40, blit=True)

Key arguments:

  • frames can be an integer (frames 0..n-1), an iterable, or a generator function. Whatever it yields becomes the argument of update.
  • interval is the delay between frames in milliseconds. 40 ms is 25 frames per second.
  • blit=True redraws only the artists the update function returns, which is much faster, but you must return them (as a tuple or list).
  • init_func draws the clean background state used when blitting and for repeats.
  • repeat and repeat_delay control looping. fargs passes extra arguments to the update function.

Keep a reference! The returned anim object must stay alive (assign it to a variable). If it is garbage collected, an interactive animation silently stops, a famous source of "my animation does nothing".

Preview the frames as a filmstrip

Because update(frame) is an ordinary function, you can call it for chosen frames and snapshot each result. That is how we preview an animation here, and it is also how you test one without a window. The code below builds a travelling wave, calls the same kind of update function for six frames, and draws each state in its own panel.

Python A wave animation as a filmstrip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With a window, one FuncAnimation would replace those six panels by one panel that changes. Separating the state function (wave) from the drawing code is a good habit: it makes the update function tiny and testable.

Animating a physical system

Physics is the classic use case: advance a simulation by one small time step per frame, then draw the new state. Here a ball is thrown and bounces. The simulation function returns the whole path, and a filmstrip shows several frames with a fading trail.

Python A bouncing ball filmstrip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real animation, the update function would run one simulation step and call ball.set_data(...). Precomputing the path, as above, is often simpler and more reproducible: update(i) just reads path[i].

Another example: sorting

Algorithm animations work the same way: each step of the algorithm is a frame. A generator makes this easy, because frames= can be a generator that yields the array after each swap. Here we capture the states of a bubble sort and show a few of them as bar charts.

Python Bubble sort states as a filmstrip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Saving and showing animations

Where does the movie come from? Three routes, each needing a writer or player:

Python
anim.save("wave.gif", writer="pillow", fps=25)     # needs the Pillow package
anim.save("wave.mp4", writer="ffmpeg", fps=25)     # needs the ffmpeg program installed
html = anim.to_jshtml()                            # self-contained HTML player for notebooks
  • GIF with the Pillow writer is simple and plays everywhere, but files are large and limited to 256 colours.
  • MP4 with ffmpeg is small and smooth; it is the right choice for long or detailed clips.
  • to_jshtml() and HTML(anim.to_jshtml()) embed a player in a Jupyter notebook without a video file.
  • In a normal script, plt.show() opens an interactive window that plays the animation live (this needs a GUI backend, see Interactivity and Widgets).

ArtistAnimation is the second class. Instead of an update function you give it a list of lists of artists, one inner list per frame. It is easy to understand, but every frame's artists stay in memory, so it is only good for short animations.

Writers, players and the HTML5 video

anim.save(...) hands the frames to a writer, a small class that knows one output format. animation.writers.list() shows which writers your installation can use, and animation.writers.is_available("ffmpeg") tells you whether the ffmpeg program was found. Matplotlib ships three families:

Writer Output Needs
PillowWriter ("pillow") animated GIF (or APNG/WebP with Pillow) the Pillow package, which Matplotlib already requires
FFMpegWriter ("ffmpeg") MP4, WebM and other video formats the ffmpeg program on the PATH
HTMLWriter ("html") a folder of frames plus an HTML page with a player nothing extra

Pass either the name (writer="pillow") or an instance when you need options: PillowWriter(fps=15), FFMpegWriter(fps=30, bitrate=1800). anim.save(path, dpi=100) controls the frame size just like savefig. Three methods produce embeddable output without writing a file yourself: anim.to_jshtml() returns a self-contained HTML player with every frame embedded as an image (heavy, but needs no ffmpeg), anim.to_html5_video() returns a <video> tag with the movie inlined as base64 (needs ffmpeg), and HTML(...) from IPython displays either in a notebook. Set rcParams["animation.html"] = "jshtml" and a notebook will show the animation as soon as the last line of a cell is the FuncAnimation object.

Python Writers: GIF, HTML player and the missing ffmpeg

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The GIF was written to a temporary folder, its header GIF89a proves it is a real GIF, and the HTML player holds all 20 frames. The video call fails here because there is no ffmpeg in the browser runner; on your computer, install ffmpeg and it works. interval (milliseconds between frames) matters for live display, while fps matters for saved files: for smooth output keep 1000 / interval and fps equal, or the saved file will play at a different speed from your window. Two more FuncAnimation keywords are worth knowing: repeat=False stops after one pass, and blit=True redraws only the artists your update function returns, so it must return them.

Performance tips

Animations redraw many times, so the cost of one frame matters.

  • Update, do not recreate. Call line.set_data rather than ax.plot every frame, which would pile up new artists and slow down each frame.
  • Use blit when you can, and return the changed artists. Text and axis labels that change (like a title) need blit=False or must be returned too.
  • Fix the limits with set_xlim and set_ylim once; autoscaling every frame is slow and makes the view jump.
  • Reduce the work per frame: fewer points, rasterized=True for heavy artists, a lower dpi for saved files.
  • Pick the frame count deliberately: duration = frames * interval. Doubling the frames of a smooth motion rarely improves it.
  • Close figures you no longer need with plt.close(fig), especially when you generate many animations in a loop.

When an animation looks wrong, call your update function manually for a few frame numbers and plot the results as a filmstrip, as in this lesson. Bugs in the state logic show up immediately.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the interval argument of FuncAnimation mean?

    interval is the pause between two frames in milliseconds. 40 ms gives 25 frames per second; the total duration is frames times interval.
  2. 2. What must the update function return when blit=True?

    Blitting redraws only the artists you return. If you forget to return them, they will not be updated on screen.
  3. 3. Why should you assign the FuncAnimation object to a variable?

    The animation object owns the timer that drives the frames. If you do not keep a reference, it can be collected and the animation silently stops.
  4. 4. Which approach is best for performance inside the update function?

    Updating existing artists is much cheaper than recreating them, which accumulates objects and forces more work per frame.
  5. 5. How can you check an animation's state logic without a window or a video writer?

    The update function is plain Python, so calling it for selected frames and drawing each result shows exactly what the animation would show.

Summary

  • An animation changes one figure between frames; FuncAnimation(fig, update, frames, interval, blit) calls update(frame) repeatedly.
  • frames may be a number, an iterable or a generator; interval is in milliseconds; blit=True redraws only the returned artists.
  • Keep a reference to the animation object, fix axis limits, and update artists with set_data instead of creating new ones.
  • Saving needs writers: Pillow for GIF, ffmpeg for MP4, or to_jshtml() for notebooks.
  • ArtistAnimation replays prepared artists and is memory hungry.
  • A filmstrip of selected frames previews and debugs an animation, and is what works on a static page.

Next, respond to the mouse and keyboard in Interactivity and Widgets.