Animate quadratic grid changes (matshow)

前端 未结 2 1047
遥遥无期
遥遥无期 2020-12-14 23:01

I have a NxN grid with some values, which change every time step. I have found a way to plot a single grid configuration of this with matshow function, but I do

2条回答
  •  青春惊慌失措
    2020-12-14 23:34

    matplotlib 1.1 has an animation module (look at the examples).

    Using animation.FuncAnimation you can update your plot like so:

    import numpy as np
    import matplotlib.pyplot as plt 
    import matplotlib.animation as animation
    
    def generate_data():
        a = np.arange(25).reshape(5, 5)
        b = 10 * np.random.rand(5, 5)
        return a - b 
    
    def update(data):
        mat.set_data(data)
        return mat 
    
    def data_gen():
        while True:
            yield generate_data()
    
    fig, ax = plt.subplots()
    mat = ax.matshow(generate_data())
    plt.colorbar(mat)
    ani = animation.FuncAnimation(fig, update, data_gen, interval=500,
                                  save_count=50)
    plt.show()
    

    You can save the animation using:

    ani.save('animation.mp4')
    

    I you save it with

    ani.save('animation.mp4', clear_temp=False)
    

    the frames are conserved and you can create an animated gif like the following with

    convert *.png animation.gif
    

    enter image description here

提交回复
热议问题