Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate quadratic grid changes (matshow)

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 don't know how do I update the status with every time step. Here is a simple example:

from pylab import *
from matplotlib import pyplot

a = arange(25)
a = a.reshape(5,5)
b = 10*rand(5,5)
matshow(a-b, cmap = cm.jet)
colorbar()
show()

This code produces the following picture: enter image description here
Now imagine that the next time step some values change, so should this picture. This is the logic I had in mind:

from pylab import *
from matplotlib import pyplot

a = arange(25)
a = a.reshape(5,5)
time=10
for t in range(time):
    b = 10*rand(5,5)
    print b
    matshow(a-b, cmap=cm.jet)
    colorbar()
show()

This produces 10 pictures. I'd like to animate this instead producing individual pictures, and for example I'd like to choose a time step between changes (that is, frame rate).
Also, I'm open to suggestions for a different functions, if matshow is not the way to go, but please keep it simple, I'm relatively inexperienced.

like image 880
enedene Avatar asked May 03 '12 10:05

enedene


1 Answers

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

like image 162
bmu Avatar answered Oct 01 '22 00:10

bmu