Animation


An animation is a sequence of images displayed one after the other. It is a powerful way to show a process or a change over time. This page shows how to build animated charts with Python and Matplotlib.

⏱ Quick start

An animated chart can be build with python using theFuncAnimation() function from matplotlib. We follow these steps:

  • Load libraries
  • Open a dataset
  • Define an update function used to build each frame of the animation
  • Create the animation with FuncAnimation() and save it with save()
Animation with python
# libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# read the data (on the web)
data = pd.read_csv('https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/gapminderData.csv')
data['continent'] = pd.Categorical(data['continent'])

# create animation
fig, ax = plt.subplots(figsize=(10, 10), dpi=120)
def update(frame):
    ax.clear()
    yearly_data = data.loc[data.year == frame, :]
    ax.scatter(
        x=yearly_data['lifeExp'], 
        y=yearly_data['gdpPercap'], 
        s=yearly_data['pop']/100000,
        c=yearly_data['continent'].cat.codes, 
        cmap="Accent",
    )
    return ax
ani = FuncAnimation(fig, update, frames=data['year'].unique())
ani.save('quick-anim.gif', writer='imagemagick', fps=1)

How to install Image Magick

Installing Image magick can be a nightmare. The official documentation is here. The best way to install it if you're on Mac OS is to use Homebrew as follow:

brew install imagemagick

Advanced use case

This real life example illustrates the power of animated charts. The chart is a stacked area chart with a text that is written through the animation.


Animation with python

Matplotlib logoMatplotlib and Image Magick

Let's start with a ver basic animated scatter plot made with python, matplotliband image magick. The scatter() function is used to build a scatterplot at each iteration of a loop. savefig() is used to save each chart at .png format. Finally,image magick builds the gif.

Basic animated scatterplot with python

The process is pretty much the same for a 3d chart. Here is an example with an animated volcano plot. Each iteration of the loop changes the camera angle, giving this feeling of travelling around the volcano.

Animated volcano plot with Python

💡 Animation ≠ Interaction

There is a common confusion between what animated and interactive charts are:

  • Animated means a sequence of several static images is displayed. The user can't do anything except watching those images.
  • Interactive means the user can interact with the chart: zoom in, hover over a shape to get a tooltip, click to have a menu... The user is not a spectator anymore, but also an actor.

Contact


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥