Beginners’ Guide to Animate Plots with matplotlib.animation

Qiaofeng Liu
6 min readApr 13, 2022

--

Fig 1. Animation of finding the maximum of f(x) through Simulated Annealing

Introduction

Animation is entertaining and an ideal way to visualize the changes or the evolvement. Also, as human beings, we are always more attracted to the “live, moving, interactive” things other than the “still, static” ones. The popularity of movies, cartoons, and video games can account for this in some sense. Therefore, it is helpful to animate our plots (or data visualizations, in general) for attracting more attention and displaying things straightforwardly.

Fig 1 is the animation of finding the maximum of f(x) through Simulated Annealing. We can see that random points (called “individuals in the population”) are initialized across the line at the beginning and gradually assemble at the maximum as the algorithm runs. This example may give you a brief idea of why animation is powerful.

Today, thanks to the prosperity of Python’s developer community, we can quickly create our animations of plots in a few lines of code. In this article, I would like to introduce how to animate plots with matplotlib.animation. I will first talk about how to set up the environment. Then, I will walk you through a simple example of animation. Next, I will show you more complex examples. And finally, I will conclude and highlight the critical points of creating animations of plots.

Setting Up the Environment

We will be using Python to animate our plots throughout this article. Matplotlib and NumPy are also required to be preinstalled. Here, we can use pip to install their latest versions.

python3 -m pip install -U matplotlib
pip install numpy

For saving the animation as a gif file, we need to install ImageMagick.

ImageMagick can resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses, and Bézier curves.

ImageMagick is also the default and recommended gif generator of matplotlib.animation. You can check out https://imagemagick.org/script/download.php for more details about how to install ImageMagick on your home operating system.

For saving the animation as an mp4 file, we need to install FFmpeg.

FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created.

You can check out https://ffmpeg.org/download.html for more details about how to install FFmpeg on your home operating system. To learn more about FFmpeg, you can also check out FFmpeg’s documentation.

Get Your Hands Dirty!

Now, it is time to get your hands dirty! We will start by writing and running our first animation.

Fig 2. Animation of the Line Plot

You can copy the above example to a script file and run it first. It will output a gif file named “animation_drawing.gif,” which will look like Fig 2. We can see that the plot is live and “grows” periodically from left to right, while the axes are fixed and unchanged. Let’s dive deeper into the code to understand what it is doing.

First, we initialize the function that we are visualizing. Here, I take sin as an example. Note that x and y are lists.

x = np.linspace(0, 10)
y = np.sin(x)

Then, we need to initialize the figure objects fig and ax and plot a “backbone”. Note that we need to obtain the plotted object line here for further updates.

fig, ax = plt.subplots()
line, = ax.plot(x, y)

We also need to write the update function. This function is an essential part of our animation. Animation is an “illusion”: in each frame, the plotted object is updated using the update function; all frames are saved as a file (either a gif file or an mp4 file) at the end (we can see it later).

def update(num, x, y, line):
line.set_data(x[:num], y[:num])
return line,

Next, it comes to the core part of this example. We now construct an FuncAnimation object to really perform the animation.

ani = animation.FuncAnimation(fig, update, len(x), interval=100,
fargs=[x, y, line], blit=True)

The first two arguments are simply fig (the figure object) and update (the function for updating the plotted object in each frame). The third argument passed into the constructor is len(x), which indicates the total number of data points (recall that x and y are lists). This is exactly the num parameter passed to update! In each frame, a value ranging from 1 to len(x) is given to the update function for generating different plots. These plots form the “illusion” of animation. The argument interval is the delay between frames in milliseconds, which is set to be 100ms in this case. The argument fargs is a tuple containing other arguments (besides num) passed to the update function, which is a tuple of x, y and line in the same order. The last argument blit is set to “True” for optimizing the result. (There are many other parameters in the constructor of FuncAnimation. You can check out FuncAnimation’s documentation for more.)

Finally, the save method of the FuncAnimation object is called to save the animation. Here, we save ani to a gif file using the gif generator imagemagick. Here, we set the frame rate fps to be 60.

ani.save('animation_drawing.gif', writer='imagemagick', fps=60)

From this example, we can conclude that the code should consist of 4 essential parts:

  1. Initialize the figure objects figand ax
  2. Write the update function
  3. Construct a FuncAnimation object to perform the animation
  4. Call save method of the FuncAnimation object to save the animation

And More Examples…

After walking through the above simple example, you may wonder what other animation we can achieve with matplotib.animation. Next, I would like to show you how we can animate the bar plot and achieve the “Bar Chart Race” effect. I adopted the code from Pratap Vardhan’s blog and adjusted the styles. The dataset used in this example is the city populations dataset, which contains the populations of cities worldwide from the 1700s to 2018. I animated the changes in the populations of the most populated cities from 1968 to 2018.

Fig 3. Animation of the Bar Plot (“Bar Chart Race”)

We can also break the code down and identify the four essential parts.

Firstly, initialize the figure objects fig and ax:

fig, ax = plt.subplots(figsize=(15, 8))

Secondly, write the update function:

def update(year):
... ... ...
... ... ...

Thirdly, construct a FuncAnimation object to perform the animation:

ani = animation.FuncAnimation(fig, update, frames=range(1968, 2019))

And lastly, call save method of the FuncAnimation object to save the animation:

ani.save('animation_drawing2.gif', writer='imagemagick', fps=20)

Besides 2D animations, we can also animate the plots in 3D with matplotlib.animation. The animation below is taken from Matplotlib’s example gallery.

Fig 4. 3D Animation

Conclusion

In conclusion, there are four essential parts of code you should write when you animate plots with matplotlib.animation.

  1. Initialize the figure objects figand ax
  2. Write the update function
  3. Construct a FuncAnimation object to perform the animation
  4. Call save method of the FuncAnimation object to save the animation

You also need to ensure that the environment is correctly set up before running your code.

And finally, there is more you can do with matplotlib.animation. Only the sky is the limit of your imagination! If you are interested in learning more, please check out the official documentation of matplotlib.animation.

References

The Wikipedia page of Simulated Annealing. https://en.wikipedia.org/wiki/Simulated_annealing

The official documentation of matplotlib.animation. https://matplotlib.org/stable/api/animation_api.html

Pratap Vardhan’s blog about Bar Chart Race. https://pratapvardhan.com/blog/bar-chart-race-python-matplotlib/

Example of 3D animation. https://matplotlib.org/3.5.0/gallery/animation/random_walk.html

--

--