Animated graphs in ipython notebook

前端 未结 8 789
失恋的感觉
失恋的感觉 2020-12-30 02:01

Is there a way of creating animated graphs. For example showing the same graph, with different parameters.

For example is SAGE notebook, one can write:



        
8条回答
  •  萌比男神i
    2020-12-30 02:42

    matplotlib has an animation module to do just that. However, examples provided on the site will not run as is in a notebook; you need to make a few tweaks to make it work.

    Here is the example of the page below modified to work in a notebook (modifications in bold).

    
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    from matplotlib import rc
    from IPython.display import HTML
    
    fig, ax = plt.subplots()
    xdata, ydata = [], []
    ln, = plt.plot([], [], 'ro', animated=True)
    
    def init():
        ax.set_xlim(0, 2*np.pi)
        ax.set_ylim(-1, 1)
        return ln,
    
    def update(frame):
        xdata.append(frame)
        ydata.append(np.sin(frame))
        ln.set_data(xdata, ydata)
        return ln,
    
    ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                        init_func=init, blit=True)
    rc('animation', html='html5')
    ani
    # plt.show() # not needed anymore
    

    Note that the animation in the notebook is made via a movie and that you need to have ffmpeg installed and matplotlib configured to use it.

提交回复
热议问题