Matplotlib FuncAnimation for scatter plot

前端 未结 2 1001
北荒
北荒 2020-12-11 04:34

I am trying to use the FuncAnimation of Matplotlib to animate the display of one dot per frame of animation.

# modules
#------------------------         


        
相关标签:
2条回答
  • 2020-12-11 05:07

    The only problem with your example is how you fill the new coordinates in the animate function. set_offsets expects a Nx2 ndarray and you provide a tuple of two 1d arrays.

    So just use this:

    def animate(i):
        data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
        scat.set_offsets(data)
        return scat,
    

    And to save the animation you might want to call:

    anim.save('animation.mp4')
    
    0 讨论(0)
  • 2020-12-11 05:19

    Disclaimer, I wrote a library to try and make this easy but using ArtistAnimation, called celluloid. You basically write your visualization code as normal and simply take pictures after each frame is drawn. Here's a complete example:

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import numpy as np
    from celluloid import Camera
    
    fig = plt.figure()
    camera = Camera(fig)
    
    dots = 40
    X, Y = np.random.rand(2, dots)
    plt.xlim(X.min(), X.max())
    plt.ylim(Y.min(), Y.max())
    for x, y in zip(X, Y):
        plt.scatter(x, y)
        camera.snap()
    anim = camera.animate(blit=True)
    anim.save('dots.gif', writer='imagemagick')
    

    0 讨论(0)
提交回复
热议问题