Embedding animation into Jupyter Notebook

There are several examples on animations in Jupyter Notebook on NumFys. Here, we will briefly mention a few pitfalls and a few tricks and hints.

When making an animation, one needs to include a few (additional) packages:

import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import display, Image

It is in general more inconvenient to create animations in Jupyter Notebook than in "ordinary" Python. In Jupyter notebook we need to embed the animation as HTML. This can be achieved in several ways.

Storing animation locally

Consider the example from the notebook on Partial Differential Equations:
(note that u and x is defined earlier and that matplotlib.pyplot is imported as plt)

from matplotlib import animation
from IPython.display import HTML

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 1), ylim=(-6, 10))
line, = ax.plot([], [], lw=1)

# Initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# Animation function which updates figure data.  This is called sequentially
def animate(i):
    line.set_data(x, u[i,:])
    return line,

# Call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=Nt, interval=20, blit=True)


# Call function to display the animation

The function HTML() from IPython.display embeds the HTML5 animation created by anim.to_html5_video().

An alternative method for embedding animations is by storing the animation locally (e.g. as gif, mp4 or html5) and then opening the file within the notebook. In the above example, one can store the animation in a file by using

anim.save('filename.gif', writer='ffmpeg')

The animation can in turn be opened from Python using

from IPython.display import Image
with open('filename.gif','rb') as file:
    display(Image(file.read()), format='png')

or within markdown using HTML.

Hints and Pitfalls