[PYTHON] Easy animation with matplotlib (mp4, gif)

matplotlib.animation: A handy animation generation library based on matplotlib.

Installation

@mac


$ pip install matplotlib
$ brew install imagemagick #For gif storage
$ brew install ffmpeg #For mp4 storage

matplotlib.Fix rc


$ python -c "import matplotlib;print(matplotlib.matplotlib_fname())"
/Users/riki/.pyenv/versions/ML-2.7.13/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc
$ atom /Users/riki/.pyenv/versions/ML-2.7.13/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc

# line 38
- backend : macosx
+ backend : Tkagg

There are two types of functions that generate Animation

Personally, Artist Animation is easier to understand, so I recommend this. FuncAnimation is more flexible, but I don't feel any inconvenience with Artist Animation.

ArtistAnimation

animation.ArtistAnimation(fig, artists, interval=200)

Note that it is easy to get an error where the artists argument must be a list of list. (Details will be described later)


Example 1: animation of sine wave

anim_sin_wave.py


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
x = np.arange(0, 10, 0.1)

ims = []
for a in range(50):
    y = np.sin(x - a)
    line, = plt.plot(x, y, "r")
    ims.append([line])

ani = animation.ArtistAnimation(fig, ims)
ani.save('anim.gif', writer="imagemagick")
ani.save('anim.mp4', writer="ffmpeg")
plt.show()

anim.gif

The pyplot.plot function can plot multiple graphs at once, so the return type is list.

lines = plt.plot(x1, y1, 'r', x2, y2, 'g', x3, y3, 'b')
print type(lines) # list
print len(lines) # 3
print type(lines[0]) # matplotlib.lines.Line2D

For clarity, I dare to unpack the main code to retrieve the Line2D object, then change it to list and then add it to list.

line, = plt.plot(x, y, "r")
ims.append([line])

You can save the animation as follows (anyone who likes gif or mp4)

ani.save('anim.gif', writer="imagemagick")
ani.save('anim.mp4', writer="ffmpeg")

Example 2: Animation of a 2D image

dynamic_image.py


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()

def f(x, y):
    return np.sin(x) + np.cos(y)

x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
ims = []

for i in range(60):
    x += np.pi / 15.
    y += np.pi / 20.
    im = plt.imshow(f(x, y), animated=True)
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
                                repeat_delay=1000)

ani.save('anim.gif', writer="imagemagick")
ani.save('anim.mp4', writer="ffmpeg")
plt.show()

anim.gif

Since the return type of the pyplot.imshow function is an AxesImage object, make it a list and then add it to the list.

im = plt.imshow([[]])
print type(im) # matplotlib.image.AxesImage
ims.append([im])

Recommended Posts

Easy animation with matplotlib (mp4, gif)
Animation with matplotlib
Animation with matplotlib
Create plot animation with Python + Matplotlib
Visualize cavity flow with matplotlib and save as gif animation
Easy Japanese font setting with matplotlib
Easy to draw graphs with matplotlib
Make a GIF animation with folder monitoring
Histogram with matplotlib
Animate with matplotlib
The basis of graph theory with matplotlib animation
Easy Grad-CAM with pytorch-gradcam
2-axis plot with Matplotlib
Draw an Earth-like flow animation with matplotlib and cartopy
Easy partial download of mp4 with python and youtube-dl!
Heatmap with Python + matplotlib
Band graph with matplotlib
Real-time drawing with matplotlib
Various colorbars with Matplotlib
3D plot with matplotlib
Easy debugging with ipdb
Adjust axes with matplotlib
Easy TopView with OpenCV
[IOS] GIF animation with Pythonista3. I was addicted to it.
LGTM --Compose LGTM images with videos and photos and output GIF animation
Trim mp4 video with python-ffmpeg
Easy tox environment with Jenkins
[Co-occurrence analysis] Easy co-occurrence analysis with Python! [Python]
Create 3d gif with python3
Graph drawing method with matplotlib
Easy folder synchronization with Python
Easy image classification with TensorFlow
Graph Excel data with matplotlib (2)
Stackable bar plot with matplotlib
Easy Python compilation with NUITKA-Utilities
Easy HTTP server with Python
Easy proxy login with django-hijack
Gradient color selection with matplotlib
Bubble sort with fluffy animation
Animate multiple graphs with matplotlib