Inline animations in Jupyter

前端 未结 5 1843
再見小時候
再見小時候 2020-11-28 23:19

I have a python animation script (using matplotlib\'s funcAnimation), which runs in Spyder but not in Jupyter. I have tried following various suggestions such as adding \"%

5条回答
  •  再見小時候
    2020-11-29 00:04

    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.

提交回复
热议问题