In this recipe, we will explore how to animate our figures. Sometimes it is more descriptive to have pictures moving in animations to explain what happens if we change the values of variables. Our main library has limited but usually sufficient animation capabilities and we will explain how to use them.
The framework for animation is added to standard matplotlib from version 1.1 and its main class is
matplotlib.animation.Animation
. This class is the base class, which is to be subclassed for specific behavior, as is the case with the classes already provided: TimedAnimation
, ArtistAnimation
, and FuncAnimation
.
In order to be able to save animations in a video file, we must have the ffmpeg
or mencoder
installer. Installation of these packages varies depending on the OS used, and changes by different releases, so we must leave it to the dear reader to Google the valid information.
Here is the code listing to demonstrate some matplotlib animations:
import numpy as np from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) def init(): """Clears current frame.""" line.set_data([], []) return line, def animate(i): """Draw figure. @param i: Frame counter @type i: int """ x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) * np.cos(22 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, # This call puts the work in motion # connecting init and animate functions and figure we want to draw animator = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)# set blit to False if you're under OS X! # This call creates the video file. # Temporary, every frame is saved as PNG file # and later processed by ffmpeg encoder into MPEG4 file # we can pass various arguments to ffmpeg via extra_args animator.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'], writer='ffmpeg_file') plt.show()
This will create the basic_animation.mp4
file in the folder you started this file from, and also displays a figure window with the running animation. The video file can be opened with most modern video players that support the MPEG-4 format. The figure (frame) should look like this:
Most important are the init()
, animate()
, and save()
functions. We first construct FuncAnimate
by passing two callback functions to it, init
and animate
. Then, we call the save
method to save our video file. More details on each function are in the following table:
The usage of matplotlib.animation.ArtistAnimation
differs from FuncAnimation
in that we must draw each artist beforehand and then instantiate the
ArtistAnimation
class with all the different frames of the artist. ArtistAnimation
is a kind of a wrapper of the matplotlib.animation.TimedAnimation
class that draws frames every N milliseconds, thus supporting time-based animation.