Introduction: Animation With Python and Matplotlib

Ever wanted to make a cool animation ?

I will show you the basics when it comes to 2D animation with Python and Matplotlib.

The video above in an example of what we are going to make.

You can download the code from mywebsite

Step 1: The Code

First we have to import all the necessary modules and functions

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation,FFMpegFileWriter

Then we create a figure and its axis. We also create an numpy array f which will contain the frames at which we will draw our animation.

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'r', animated=True)
f = np.linspace(-3, 3, 200)

The init function will allow us to initialize the data and also to set the axis limits.

def init():
	ax.set_xlim(-3, 3)
	ax.set_ylim(-0.25, 2)
	ln.set_data(xdata,ydata)
	return ln,

The update function will update the plot at each frame.

def update(frame):
	xdata.append(frame)
	ydata.append(np.exp(-frame**2))
	ln.set_data(xdata, ydata)
	return ln,

Then what is left is to animate the whole thing.

ani = FuncAnimation(fig, update, frames=f,
                    init_func=init, blit=True, interval = 2.5,repeat=False)
plt.show()	

And then if you want to save the file you can use :

mywriter = FFMpegFileWriter(fps=25,codec="libx264")
ani.save("test.mp4", writer=mywriter)

This requires ffmpeg whose installation is the subject of another instructable