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)
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()
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")
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()
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