Animate quadratic grid changes (matshow)

前端 未结 2 1040
遥遥无期
遥遥无期 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:33

    The easiest way is probably to have matplotlib save individual images and then have another program or library stitch together them to an animation. This approach uses a module called write2gif but you can also use mencoder, ffmpeg or any other software capable of producing video:

    from images2gif import writeGif
    from pylab import *
    from matplotlib import pyplot as plt
    from PIL import Image
    
    a = arange(25)
    a = a.reshape(5,5)
    time=10
    images = []
    for t in range(time):
        fig = plt.figure(figsize = (5, 5))
        ax = fig.add_subplot(111)
        b = 10*rand(5,5)
        cax = ax.matshow(a-b, cmap=cm.jet, vmin = -8, vmax = 24)
        fname = 'tmp%03d.png' % t
        fig.colorbar(cax)
        fig.savefig(fname)
        images.append(Image.open(fname))
    writeGif('matanim.gif', images, duration = .2)    
    

    Here is an example on how to do it from within pylab's interface. It doesn't work so well since the continuous rendering runs in the same thread as pylabs gui handlers:

    from pylab import arange, cm, draw, rand
    from matplotlib import pylab as plt
    from time import sleep
    plt.ion()
    a = arange(25)
    a = a.reshape(5,5)
    fig = plt.figure(figsize = (5, 5))
    for i in range(200):
        ax = fig.add_subplot(111)
        b = 10*rand(5,5)
        cax = ax.matshow(a-b, cmap=cm.jet, vmin = -8, vmax = 24)
        if i == 0:
            fig.colorbar(cax)
        draw()
        sleep(0.2)
    
    0 讨论(0)
  • 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

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