Animation

Animation#

You can use animation class of matplotlib to show animations.

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

After downloading the code, please uncomment the line %matplotlib notebook to see animations.

%matplotlib inline
#%matplotlib notebook

FuncAnimation#

It is often helpful to visualize the data while they are computed, rather than after all computations are done.
For that, you can define a function to draw each frame, and pass the function to FuncAnimation.

We will see defining your own function in Chapter 4, but here is an example.

def pendulum(i, clear=True, dt=0.05):
    """swinging pendulum. i:frame number"""
    # clear previous plot
    if clear:
        plt.cla()
    # swinging pendulum
    l = 1  # length
    th = np.sin(np.pi*i*dt)  # angle, 2 sec period
    x = np.sin(th)
    y = -np.cos(th)
    # draw a new plot
    pl = plt.plot([0, x], [0, y], 'b')
    plt.axis('square')
    plt.xlim(-1.2*l, 1.2*l)
    plt.ylim(-1.2*l, 1.2*l)
    return pl   # for saving
fig = plt.figure()
anim = animation.FuncAnimation(fig, pendulum, frames=40, interval=50)
_images/d63b21113996caa765b5de8c7e2dd6453941d1bc06aba5864de0b72dd0799103.png

ArtistAnimation#

You can alternatively save all frames in an array and animate at once.

fig = plt.figure()
frames = []  # prepare frames
for i in range(40):
    art = pendulum(i, False)
    # append to the frame
    frames.append(art)
anim = animation.ArtistAnimation(fig, frames, interval=50)
_images/20786155dd3fef26357b797a4d048cf7d94b737e2ef2c60f0a9116000596925d.png

You can save the movie in a motion gif file.

anim.save("pend.gif", writer='pillow')

Here is the saved file pend.gif: pend.gif