# Animating plots and waves in Python using matplotlib

matplotlib is an amazing framework to do visual plots in Python. It compares well with GnuPlot and beats Matlab’s plotting abilities by having more features. Although it does lack some 3D support, you may simply choose a different framework for 3D plots thanks to Python’s flexibility . In which case I would recommend Mayavi as a superb 3D plotting engine which I have written about before.

But now, let’s have a look at matplotlib’s animation capabilities. The script below shows a very easy approach to animation in matplotlib. This results in an animation of the standing wave shown here:

The script is as follows:

from matplotlib.pylab import *  # pylab is the easiest approach to any plotting
import time                     # we'll do this rendering i real time

ion()                           # interaction mode needs to be turned off

x = arange(0,2*pi,0.01)         # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x)               # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3)        # set the range for our plot

starttime = time.time()         # this is our start time
t = 0                           # this is our relative start time

while(t < 5.0):                 # we'll limit ourselves to 5 seconds.
# set this to while(True) if you want to loop forever
t = time.time() - starttime # find out how long the script has been running
y = -2*sin(x)*sin(t)        # just a function for a standing wave
# replace this with any function you want to animate
# for instance, y = sin(x-t)

line.set_ydata(y)           # update the plot data
draw()                      # redraw the canvas

I’ve commented each line, since the script is fairly small, but let’s outline a few important things.

First of all, you need to disable interactive mode with

ion()

This makes it possible to animate, but disables all the button controls in matplotlib’s figure window.

Furthermore, we need to assign our plot to a variable (or pointer if you like), named line. This is done by plotting some dummy data:

line, = plot(x,x)

Note the comma after “line”. This is placed here because plot returns a list of lines that are drawn. Since we draw only one line we unpack only this by placing a comma and nothing else after “line”. If you plot multiple lines at once you may unpack them together by issuing a command like this:

line_a,line_b,line_c = plot(...

This plotting makes our axes aligned to the dummy data (in this case y = x). To make sure we have enough room, we manually set the limits of our y axis:

line.axes.set_ylim(-3,3)

Finally, we do our calculations and eventually change the y-data for each time step. After this, we draw everything back onto the canvas. This is done through the following two lines:

    line.set_ydata(y)           # update the plot data
draw()                      # redraw the canvas

That’s it. Your animation should now look like the one above.

### Saving the animation to a  file

Saving everything to file is fairly simple with the savefig command. You can save all the frames as images and then convert them to video using your favorite video editor. I recommend using ffmpeg from command line or Blender (which also does 3D). There are surely easier tools out there, but I find the work flow using ffmpeg and Blender quite quick, and they are also useful tools for many other tasks.

I’ve made the script animation ready below, and there’s really just one important thing to note: Earlier we showed the animation in real time. Saving all the images in real time lags badly and many frames are dropped. Because of this, we now set a delta time between each frame and iterates over each and every frame to make sure we have enough data for a smooth video.

Feel free to use the script below as it suits you:

from matplotlib.pylab import *  # pylab is the easiest approach to any plotting

ion()                           # interaction mode needs to be turned off

fig = figure(figsize=(16,9),dpi=80)     # create a figure in 1280 x 720 pixels
# this is not as simple as it could be, but
# it is like this because matplotlib is focused
# on print, not screen

x = arange(0,2*pi,0.01)         # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x)               # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3)        # set the range for our plot

t = 0                           # this is our relative start time
dt = 0.04
i = 0
while(t < 5.0):                 # we'll limit ourselves to 5 seconds.
# set this to while(True) if you want to loop forever
y = -2*sin(x)*sin(t)        # just a function for a standing wave
# replace this with any function you want to animate
# for instance, y = sin(x-t)

line.set_ydata(y)           # update the plot data
draw()                      # redraw the canvas

t = t + dt                  # increase the time
i = i + 1                   # increase our counter

# save the figure with a 4-digit number
savefig("outdata/blah" + '%04d' % i + ".png")

## 6 thoughts on “Animating plots and waves in Python using matplotlib”

1. ola , boa explicação !

• Desculpe , escrevi em português …

Boa explicação !

2. Is there a way to save the animation in a movie without using a external tool?

• I’m afraid there are no built-in movie tool in matplotlib. Earlier I’ve been using ffmpeg to convert the .png files to a movie, but other command line tools such as mencoder and ImageMagick should do the trick. You may also try out Blender or some other GUI tool to do the conversion.

It’s sad that there is no straight-forward way with matplotlib, but I kind of understand it, since video encoding is a whole different playing field and maintaining it would require a lot of work.