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

We use %matplotlib wideget for interactive graphics.

#%matplotlib notebook
%matplotlib widget

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, repeat=False)
anim.event_source.stop() # animation keeps repeating without this

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, repeat=False)
anim.event_source.stop() # animation keeps repeating without this
/Users/doya/miniforge3/lib/python3.12/site-packages/matplotlib/animation.py:908: UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you output the Animation using `plt.show()` or `anim.save()`.
  warnings.warn(

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