How to animate a scatter plot?

后端 未结 4 1882
清酒与你
清酒与你 2020-11-22 17:18

I\'m trying to do an animation of a scatter plot where colors and size of the points changes at different stage of the animation. For data I have two numpy ndarray with an x

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 17:44

    I wrote celluloid to make this easier. It's probably easiest to show by example:

    import matplotlib.pyplot as plt
    from matplotlib import cm
    import numpy as np
    from celluloid import Camera
    
    numpoints = 10
    points = np.random.random((2, numpoints))
    colors = cm.rainbow(np.linspace(0, 1, numpoints))
    camera = Camera(plt.figure())
    for _ in range(100):
        points += 0.1 * (np.random.random((2, numpoints)) - .5)
        plt.scatter(*points, c=colors, s=100)
        camera.snap()
    anim = camera.animate(blit=True)
    anim.save('scatter.mp4')
    

    It uses ArtistAnimation under the hood. camera.snap captures the current state of the figure which is used to create the frames in the animation.

    Edit: To quantify how much memory this uses I ran it through memory_profiler.

    Line #    Mem usage    Increment   Line Contents
    ================================================
        11     65.2 MiB     65.2 MiB   @profile
        12                             def main():
        13     65.2 MiB      0.0 MiB       numpoints = 10
        14     65.2 MiB      0.0 MiB       points = np.random.random((2, numpoints))
        15     65.2 MiB      0.1 MiB       colors = cm.rainbow(np.linspace(0, 1, numpoints))
        16     65.9 MiB      0.6 MiB       fig = plt.figure()
        17     65.9 MiB      0.0 MiB       camera = Camera(fig)
        18     67.8 MiB      0.0 MiB       for _ in range(100):
        19     67.8 MiB      0.0 MiB           points += 0.1 * (np.random.random((2, numpoints)) - .5)
        20     67.8 MiB      1.9 MiB           plt.scatter(*points, c=colors, s=100)
        21     67.8 MiB      0.0 MiB           camera.snap()
        22     70.1 MiB      2.3 MiB       anim = camera.animate(blit=True)
        23     72.1 MiB      1.9 MiB       anim.save('scatter.mp4')
    

    To summarize this:

    • Creating 100 plots used 1.9 MiB.
    • Making the animation used 2.3 MiB.
    • This method of making animations used 4.2 MiB of memory in sum.

提交回复
热议问题