Animation with matplotlib

Overview

You can easily create good-looking graphs using python's matplotlib. The function to create graph animation is also provided as standard in matplotlib, so here is a comprehensive summary of how to use it.

Creating an animation

There are two main methods offered:

--Animation by passing a list of graph objects created in advance (ArtistAnimation) --Define a function for updating the graph and animate it (FuncAnimation)

The reason for the former is Artist Animation, because matplotlib calls graph objects artists. We will use that name here as well. If you need some performance, or if you need to change the title or fine control in the animation, you should choose the latter.

Let's introduce each with a code example.

ArtistAnimation

Passing to ArtistAnimation is a list of artists' list [^ 1]. If each frame of the animation is represented by frame 1, frame 2, ...,


[
  [
Artist displayed in frame 1_1,Artist displayed in frame 1_2, ...
  ],
  [
Artist displayed in frame 2_1,Artist displayed in frame 2_2, ...
  ],
  ...
]

It will be. Note that some matplotlib graph types and functions return an artist and some return a list of artists. For example, the following example appends the list of artists returned from the plot function as it is.

import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
import numpy as np
fig, ax = plt.subplots()
artists = []
x = np.arange(10)
for i in range(10):
    y = np.random.rand(10)
    im = ax.plot(x, y)
    artists.append(im)
anim = ArtistAnimation(fig, artists, interval=1000)
fig.show()

For functions that return an artist, such as scatter, append the one wrapped in the list.

import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
import numpy as np
fig, ax = plt.subplots()
artists = []
x = np.arange(10)
for i in range(10):
    y = np.random.rand(10)
    im = ax.scatter(x, y)
    artists.append([im])
anim = ArtistAnimation(fig, artists, interval=1000)
fig.show()

FuncAnimation

A function is called for each frame of the animation. There can be two patterns of processing:

--Create a new artist every time (you need to keep the previously created artist and delete it explicitly) --Update the created artist data

I will introduce each code.

Creation pattern

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig, ax = plt.subplots()
ims = []
x = np.arange(10)

ax.set_xlim(0, 9)
ax.set_ylim(0, 1)

def update_anim(i):
    y = np.random.rand(10)
    if len(ims) > 0:
        im = ims.pop()
        im.remove()
    im, = ax.plot(x, y)
    ims.append(im)

anim = FuncAnimation(fig, update_anim, interval=1000)
fig.show()

Data update pattern

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig, ax = plt.subplots()
artists = []
im, = ax.plot([], [])
x = np.arange(10)
ax.set_xlim(0, 9)
ax.set_ylim(0, 1)

def update_anim(frame):
    y = np.random.rand(10)
    im.set_data(x, y)
    
anim = FuncAnimation(fig, update_anim, blit=False)
fig.show()

Of course, updating data is more efficient.

blit=True

Also, if you specify the optional argument "blit" to True, it seems that you can further speed up drawing using the technique called "litting" used in computer graphics. In this case, it is necessary to return the list of artists to be slitted from the function.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig, ax = plt.subplots()
artists = []
im, = ax.plot([], [])
x = np.arange(10)
ax.set_xlim(0, 9)
ax.set_ylim(0, 1)

def update_anim(frame):
    y = np.random.rand(10)
    im.set_data(x, y)
    return im,
    
anim = FuncAnimation(fig, update_anim, blit=True)
fig.show()

Save and share animations

The created animation can be saved in a file as follows.

Export to gif

anim.save('anim.gif', writer='imagemagick', fps=4)

Export to mp4

anim.save('anim.mp4', writer='ffmpeg', fps=4)

Also, when working on a jupyter notebook, you can specify % matplotlib nbagg instead of% matplotlib inline to display a graph that the user can interact with inline. Animation is also performed. However, it is heavy and will not be displayed in nbviewer, so if you just want to display it inline, it is recommended to embed the video as follows.

from IPython.display import HTML
HTML(anim.to_html5_video())

footnote

[^ 1]: Generally, iterable object that can be looped with for. Here, it is called a list in a general sense.

Recommended Posts

Animation with matplotlib
Animation with matplotlib
Create plot animation with Python + Matplotlib
Japanese with matplotlib
Histogram with matplotlib
Animate with matplotlib
Easy animation with matplotlib (mp4, gif)
2-axis plot with Matplotlib
Heatmap with Python + matplotlib
Band graph with matplotlib
Learn with Cheminformatics Matplotlib
Real-time drawing with matplotlib
Various colorbars with Matplotlib
3D plot with matplotlib
Adjust axes with matplotlib
The basis of graph theory with matplotlib animation
Graph Excel data with matplotlib (1)
Try using matplotlib with PyCharm
Diffusion equation animation with NumPy
Draw an Earth-like flow animation with matplotlib and cartopy
Graph Excel data with matplotlib (2)
Stackable bar plot with matplotlib
Gradient color selection with matplotlib
Bubble sort with fluffy animation
Animate multiple graphs with matplotlib
Make a gif animation from a serial number file with matplotlib
Visualize cavity flow with matplotlib and save as gif animation
A python graphing manual with Matplotlib.
Inference & result display with Tensorflow + matplotlib
Japaneseize Matplotlib with Alpine using Docker
[Python] font family and font with matplotlib
[IOS] Disassemble GIF animation with Pythonista3.
Draw Japanese with matplotlib on Ubuntu
Draw a loose graph with matplotlib
Versatile data plotting with pandas + matplotlib
Heatmap with Dendrogram in Python + matplotlib
Easy Japanese font setting with matplotlib
Easy to draw graphs with matplotlib
Continuously color with matplotlib scatter plot
Draw Lyapunov Fractal with Python, matplotlib
When matplotlib doesn't work with python2.7
Lognormal probability plot with Python, matplotlib
Write a stacked histogram with matplotlib
Implement "Data Visualization Design # 2" with matplotlib
[Introduction to Matplotlib] Axes 3D animation: I played with 3D Lissajous figures ♬
Matplotlib memorandum
How to title multiple figures with matplotlib
[Python] Set the graph range with matplotlib
Adjust the spacing between figures with Matplotlib
Align the size of the colorbar with matplotlib
Flexible animation creation using animation.FuncAnimation of matplotlib
Matplotlib gallery
Try drawing a normal distribution with matplotlib
Matplotlib memo
Make a partially zoomed figure with matplotlib
Write SVG graphs with matplotlib on heroku
Display Japanese graphs with VS Code + matplotlib
Heat Map for Grid Search with Matplotlib
Set the xticklabels color individually with matplotlib
Draw hierarchical axis labels with matplotlib + pandas
[Python] Let's make matplotlib compatible with Japanese