<jupyter_start><jupyter_text>Embedding Matplotlib Animations in IPython Notebooks *This notebook first appeared as a*[*blog post*](http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/)*on*[*Pythonic Perambulations*](http://jakevdp.github.io).*License:* [*BSD*](http://opensource.org/licenses/BSD-3-Clause)*(C) 2013, <NAME>.**Feel free to use, distribute, and modify with the above attribution.* I've spent a lot of time on this blog working with matplotlib animations(see the basic tutorial[here](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/),as well as my examples of animating[a quantum system](http://jakevdp.github.io/blog/2012/09/05/quantum-python/),[an optical illusion](http://jakevdp.github.io/blog/2012/09/26/optical-illusions-in-matplotlib/),[the Lorenz system in 3D](http://jakevdp.github.io/blog/2013/02/16/animating-the-lorentz-system-in-3d/),and [recreating Super Mario](http://jakevdp.github.io/blog/2013/01/13/hacking-super-mario-bros-with-python/)).Up until now, I've not have not combined the animations with IPython notebooks.The problem is that so far the integration of IPython with matplotlib isentirely static, while animations are by their nature dynamic.  There are someefforts in the IPython and matplotlib development communities to remedy this,but it's still not an ideal setup.I had an idea the other day about how one might get around this limitationin the case of animations.  By creating a function which saves an animationand embeds the binary data into an HTML string, you can fairly easily createautomatically-embedded animations within a notebook.  The Animation Display Function As usual, we'll start by enabling the pylab inline mode to make thenotebook play well with matplotlib.<jupyter_code>%pylab inline<jupyter_output>Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.<jupyter_text>Now we'll create a function that will save an animation and embed it inan html string.  Note that this will require ffmpeg or mencoder to beinstalled on your system.  For reasons entirely beyond my limited understandingof video encoding details, this also requires using the libx264 encodingfor the resulting mp4 to be properly embedded into HTML5.<jupyter_code>from tempfile import NamedTemporaryFile

VIDEO_TAG = """<video controls>
 <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
 Your browser does not support the video tag.
</video>"""

def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")
    
    return VIDEO_TAG.format(anim._encoded_video)<jupyter_output><empty_output><jupyter_text>With this HTML function in place, we can use IPython's HTML display toolsto create a function which will show the video inline:<jupyter_code>from IPython.display import HTML

def display_animation(anim):
    plt.close(anim._fig)
    return HTML(anim_to_html(anim))<jupyter_output><empty_output><jupyter_text>Example of Embedding an Animation The result looks something like this -- we'll use a basic animation exampletaken from my earlier[Matplotlib Animation Tutorial](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/) post:<jupyter_code>from matplotlib import animation

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

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

# animation function.  This is called sequentially
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,

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

# call our new function to display the animation
display_animation(anim)<jupyter_output><empty_output><jupyter_text>Making the Embedding Automatic We can go a step further and use IPython's display hooks to automaticallyrepresent animation objects with the correct HTML.  We'll simply set the``_repr_html_`` member of the animation base class to our HTML converterfunction:<jupyter_code>animation.Animation._repr_html_ = anim_to_html<jupyter_output><empty_output><jupyter_text>Now simply creating an animation will lead to it being automatically embeddedin the notebook, without any further function calls:<jupyter_code>animation.FuncAnimation(fig, animate, init_func=init,
                        frames=100, interval=20, blit=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09893209752166028, 'fraction_numerical': 0.02135804956679428, 'mean_word_length': 4.995169082125604, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '461867', 'license': 'MIT', 'n_tokens_mistral': 1588, 'n_tokens_neox': 1483, 'n_words': 484, 'path': 'content/downloads/notebooks/AnimationEmbedding.ipynb', 'repo_name': 'Jerska/jakevdp.github.io-source', 'size': '4972'}