A while back I wrote a post on Embedding Matplotlib Animations in Jupyter Noteboks, which became surprisingly popular. It outlined how to render Matplotlib animations in the Jupyter Notebook, by encoding it as a HTML5 video using the
to_html5_video method introduced in the release of Matplotlib 1.5.
With this awesome addition, encapsulated in the new
In this post, we demonstrate how to use this method on the same example animation from my previous post, which was originally derived from an even earlier post by Jake VanderPlas.
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML
fig, ax = plt.subplots() ax.set_xlim(( 0, 2)) ax.set_ylim((-2, 2)) line, = ax.plot(, , lw=2)
Define the initialization function, which plots the background of each frame:
def init(): line.set_data(, ) return (line,)
Define the animation function, which is called for each new frame:
def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return (line,)
Compile the animation. Setting
blit=True will only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True)
Displaying the Animation¶
Now we can display this
anim object using IPython's HTML display method. For comparison, we first encode the animation and render it as an HTML5 video using the
to_html5_video method, as covered in my previous post: