Inline animations in Jupyter

notebook backend

‘Inline’ means that the plots are shown as png graphics. Those png images cannot be animated. While in principle one could build an animation by successively replacing the png images, this is probably undesired.

A solution is to use the notebook backend, which is fully compatible with FuncAnimation as it renders the matplotlib figure itself:

%matplotlib notebook

jsanimation

From matplotlib 2.1 on, we can create an animation using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs.

from IPython.display import HTML
HTML(ani.to_jshtml())

Some complete example:

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

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))

from IPython.display import HTML
HTML(ani.to_jshtml())

Alternatively, make the jsanimation the default for showing animations,

plt.rcParams["animation.html"] = "jshtml"

Then at the end simply state ani to obtain the animation.

Also see this answer for a complete overview.

Leave a Comment