Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib animations - how to export them to a format to use in a presentation?

So, I learned how to make cute little animations in matplotlib. For example, this:

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

plt.ion()

fig = plt.figure() 
ax  = fig.add_subplot(111) 

ax.set_xlim(0, 1)
ax.set_ylim(-2,2)

dt = 0.01
q  = 0.01
t = np.arange(0,1,dt)
x = np.sin(2*np.pi*t)
line, = ax.plot(t,x, '-')
fig.canvas.draw()
for i in xrange(100):
    x = (1-q) * x + q* np.random.normal(size = len(t))
    line.set_ydata(x)
    fig.canvas.draw()

This works and it's very nice. But how I use this to make a movie I can display, for example, in a pdf presentation? I tried to do fig.savefig("test.gif") but there's an error message indicating that matplotlib doesn't export gifs.

Is there a way of doing this without resorting to external tools (like making a lot of png's and stitching them together)?

like image 521
Rafael S. Calsaverini Avatar asked Dec 15 '11 18:12

Rafael S. Calsaverini


People also ask

How do I save a Matplotlib animation?

To save an animation, we can use Animation. save() or Animation. to_html5_video(). Animation.

How do I save an animation as a mp4 in Python?

To save this animation as an mp4 you can simply call ani. save() . If you just want to take a look at it before you save it call plt. show() instead.


2 Answers

In short, no there is no other way besides using an external tool. There is a new module in 1.1.0 that helps you do animations and save them to mpeg4 format. It uses an external tool to automatically do this conversion, from many frames to a single movie. You can make your gif using imagemagick's convert or use ffmpeg or mencoder, which are the two options provided by the new animation module.

like image 129
Yann Avatar answered Nov 08 '22 09:11

Yann


If you use matplotlib.animation and have something like FFmpeg in your path then this should work:

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

fig = plt.figure() 
ax  = fig.add_subplot(111) 

ax.set_xlim(0, 1)
ax.set_ylim(-2,2)

dt = 0.01
q  = 0.01
t = np.arange(0,1,dt)
x = np.sin(2*np.pi*t)
images = []

for i in xrange(100):
    x = (1-q) * x + q* np.random.normal(size = len(t))
    line, = ax.plot(t,x, '-')
    images.append((line,))

line_anim = ArtistAnimation(fig, images, interval=50, blit=True)
line_anim.save('my_animation.mp4')
plt.show()

cute, eh?

like image 36
danodonovan Avatar answered Nov 08 '22 11:11

danodonovan