Animating in matplotlib

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.

Getting ready

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.

Class name (parent class)

Description

Animation (object)

This class wraps the creation of an animation using matplotlib. It is only a base class which should be subclassed to provide the required behavior.

TimedAnimation (Animation)

The Animation subclass supports time-based animation, drawing a new frame every *interval* milliseconds.

ArtistAnimation (TimedAnimation)

Before calling this function, all plotting should have taken place and the relevant artists saved.

FuncAnimation (TimedAnimation)

Makes an animation by repeatedly calling a function, passing in (optional) arguments.

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.

How to do it...

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:

How to do it...

How it works...

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:

Function name

Usage

init

Passed to matplotlib.animation.FuncAnimation constructor via parameter init_func to clear the frame before the next frame is drawn.

animate

Passed to matplotlib.animation.FuncAnimation constructor via func parameter.

The figure we want to animate is passed via fig argument, which is passed under the hood to the matplotlib.animation.Animation constructor to connect animation events with the figure we want to draw. This function gets (optional) parameters from frames—usually iterable, representing the number of frames.

matplotlib.animation.Animation.save

Saves a movie file by drawing every frame. It creates temporary image files before processing them through the encoder (ffmpeg or mencoder) to create a video file. This function also accepts various parameters that configure video output, including metadata (author...), codec to use, and resolution/size. One of the parameters is – which defines what video encoder to use. Currently supported are ffmpeg, ffmpeg_file, and mencoder.

There's more...

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.

Note

For Mac OS X users, animation framework can unfortunately be troublesome on this platform, and sometimes simply does not work. This will improve with future releases of matplotlib.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.28.80