Inline animations in Jupyter

风格不统一 提交于 2019-11-27 11:48:35

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.

There is a simple example within this tutorial here: http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/

To summarise the tutorial above, you basically need something like this:

from matplotlib import animation
from IPython.display import HTML

# <insert animation setup code here>

anim = animation.FuncAnimation()  # With arguments of course!
HTML(anim.to_html5_video())

However...

I had a lot of trouble getting that to work. Essentially, the problem was that the above uses (by default) ffmpeg and the x264 codec in the background but these were not configured correctly on my machine. The solution was to uninstall them and rebuild them from source with the correct configuration. For more details, see the question I asked about it with a working answer from Andrew Heusser: Animations in ipython (jupyter) notebook - ValueError: I/O operation on closed file

So, try the to_html5_video solution above first, and if it doesn't work then also try the uninstall / rebuild of ffmpeg and x264.

Here is the answer that I put together from multiple sources including the official examples. I tested with the latest versions of Jupyter and Python.


    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    from IPython.display import HTML

    #=========================================
    # Create Fake Images using Numpy 
    # You don't need this in your code as you have your own imageList.
    # This is used as an example.

    imageList = []
    x = np.linspace(0, 2 * np.pi, 120)
    y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
    for i in range(60):
        x += np.pi / 15.
        y += np.pi / 20.
        imageList.append(np.sin(x) + np.cos(y))

    #=========================================
    # Animate Fake Images (in Jupyter)

    def getImageFromList(x):
        return imageList[x]

    fig = plt.figure(figsize=(10, 10))
    ims = []
    for i in range(len(imageList)):
        im = plt.imshow(getImageFromList(i), animated=True)
        ims.append([im])

    ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
    plt.close()

    # Show the animation
    HTML(ani.to_html5_video())

    #=========================================
    # Save animation as video (if required)
    # ani.save('dynamic_images.mp4')

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!