Create Animations with FuncAnimation in Python

The matplotlib.animation library contains many classes and functions to play with animations. In this post we’re going to take a look at how to create animations with matplotlib.animation.FuncAnimation.

matplotlib library icon
Image from matplotlib

matplotlib.animation.FuncAnimation Class Signature

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=100, *, cache_frame_data=True, **kwargs)

FuncAnimation is a class in matplotlib.animation. It allows us to create an animation out of a function. There are two required parameters, three optional NoneType parameters, and six optional parameters that are not NoneType. The two required parameters are fig, and func. The three optional NoneType parameters are frames, init_func, and fargs. Finally, the six optional parameters that are not NoneType are save_count, interval, repeat_delay, repeat, blit, and cache_frame_data.

Required Parameters for animation.FuncAnimation

The two required parameters for FuncAnimation are fig and func. fig is the matplotlib.figure.Figure object that we will use. It’s required to draw, resize, and change the animation. func is the function that creates each frame of the animation. The func animation is a callable function that takes frames as its first argument and fargs as its optional keyword arguments. If blit is True, then func must return an iterable, else it does not.

Default, possible NoneType, Arguments for FuncAnimation

The three possible NoneType arguments for the FuncAnimation class are frames, init_func, and fargs. The table below shows the acceptable types for each of these arguments.

ArgumentAcceptable Types
framesiterable, int, generator function, None
init_funccallable, None
fargstuple, None

frames is the data that we’ll pass the required func parameter. If it is an iterable, then the FuncAnimation object created will take the values as is and override the save_count parameter with the length of the iterable. When it’s an integer, it’s equivalent to passing the iterable range(frames). If it’s a generator function, the generator function must yield some object.

init_func is a callable function that will be called once to initialize and draw a clear frame. If this parameter is passed, it’s called once only on initialization (thus the name init_func). init_func must return an iterable.

Finally, fargs, is an optional parameter that stands for “function arguments”. When passed, it should be an ordered tuple of arguments that we want to pass to func after frames. We only need to pass this if our func argument takes multiple parameters.

Default, not NoneType, Arguments for FuncAnimation

Here we’ll go over the six default arguments for matplotlib.animation.FuncAnimation that are not allowed to be NoneType.

ArgumentRequired TypeDescription
save_countintDefaults to 100, represents the number of values from frames to cache/save.
intervalintDefaults to 200, represents the number of milliseconds between frames in the animation.
repeat_delayintDefaults to 0, represents the number of milliseconds between animations if repeat is set to True.
repeatboolDefaults to True, represents whether or not the animation should repeat.
blitboolDefaults to False, represents whether blitting should be used for the animation.
cache_frame_databoolDefaults to True, represents whether or not we want to cache the frames. Set this to false when dealing with large frames.

matplotlib.animation.FuncAnimation Functions

matplotlib.animation.FuncAnimation has seven functions, four of which have return values and three of which do not. The four functions with return values are new_frame_seq, new_saved_frame_seq, to_html5_video, and to_jshtml. The three functions without return values are pause, resume, and save.

FuncAnimation Methods with Return Values

Let’s go over the four functions from FuncAnimation that have return values. Two of these return sequences, the new_frame_seq and new_saved_frame_seq functions. new_frame_seq returns a new frame sequence. new_saved_frame_seq returns a new frame sequence from the cached/saved frames. This only works if the cache_frame_data parameter was set to True.

The other two functions with return values return strings. to_html5_video returns a string in the form of an HTML embed. You can embed this string in a website to embed the animation. to_jshtml returns a string in the form of the path to the saved file as a JSHTML file. JSHTML is a JavaScript HTML hybrid type file type that is an animation.

animation.FuncAnimation Methods without Return Values

The three FuncAnimation functions that don’t have return values are pause, resume, and save. pause and resume are pretty self-explanatory. You can call these to pause and resume the animation. save is a little more complex. 

The save method has one required parameter, and 10 optional parameters. The required parameter is a filename to save to. The optional parameters are a writer, the fps, the dpi, the video codec, a bitrate, any extra_args, file metadata, and extra_anims to include in the saved file, any extra savefig_kwargs, and a progress_callback for showing save progress. For most use cases, the writer and fps optional arguments are sufficient.

How to Make Animations with FuncAnimation

Sine Animation Animated with FuncAnimation

All we have to do to make an animation with the FuncAnimation class is to have a figure and a function. We’ll build a simple example of an animation of a Sine function, the same function we used for our Recurrent Neural Network example. To follow this example, you’ll need to install two libraries, numpy for the numerical data to plot and matplotlib (obviously) to use FuncAnimation and plot a figure. We can do this with the line below in the terminal.

pip install numpy matplotlib

Setup Animation

First let’s set up our animation with our imports, the plots, and axis. We’ll import numpy, matplotlib.pyplot, and, of course, FuncAnimation from matplotlib.animation. After our imports we have to define our plots by using plt.subplots. This allows us to plot multiple plots on the same figure.

We’ll first plot the sine function on the graph. First, we define the x values as the _range. Next, we define the y values as the sine function of that _range. Next, we’ll create the axis and the starting point for our red dot that we’ll animate.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
 
fig, ax = plt.subplots()
 
#plot sine function
_range = np.arange(0, 2*np.pi, 0.001)
sine = np.sin(_range)
line = plt.plot(_range, sine)
 
ax = plt.axis([0, 2*np.pi, -1, 1])

Setup Function to Animate

To create the red dot, we’ll start it out at (0, sin(0)). Using ”ro” in the plot function tells the plot to create a red (”r”) dot (”o”). We use dot, = because plt.plot returns a tuple, and we add the comma after the variable to unpack the tuple.

Our function will take one parameter, i, which represents the x value of the plot for our red dot. We’ll set the dot’s current position to i, and sin(i), and return the unpacked tuple.

dot, = plt.plot([0], [np.sin(0)], 'ro')
def func(i):
    dot.set_data(i, np.sin(i))
    return dot,

Call FuncAnimation to Show Animation

Now that we have the figure and the function, we can finally use matplotlib.animation.FuncAnimation. That’s what this post is all about. To use the FuncAnimation function, we’ll pass in the figure and function we made as well as frames, and interval.

_animation = FuncAnimation(fig, func, frames=np.arange(0, 2*np.pi, 0.1), interval=10)
plt.show()

Further Reading

Learn More

To learn more, feel free to reach out to me @yujian_tang on Twitter, connect with me on LinkedIn, and join our Discord. Remember to follow the blog to stay updated with cool Python projects and ways to level up your Software and Python skills! If you liked this article, please Tweet it, share it on LinkedIn, or tell your friends!

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang
Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

8 thoughts on “Create Animations with FuncAnimation in Python

Leave a Reply

%d bloggers like this: