Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...