动画二次方网格变化(matshow) [英] Animate quadratic grid changes (matshow)

查看:124
本文介绍了动画二次方网格变化(matshow)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NxN网格,其中包含一些值,每个时间步长都会改变.我已经找到了一种使用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:
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()

这将产生10张图片.我想对此进行动画处理,而不是生成单独的图片,例如,我想选择两次更改之间的时间步长(即帧频).
另外,如果不是matshow可行的方法,我也乐于接受其他功能的建议,但是请保持简单,我没有经验.

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.

推荐答案

matplotlib 1.1具有动画模块(请参见

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

使用animation.FuncAnimation,您可以像这样更新情节:

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')

我用

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

框架是保守的,您可以使用以下方式创建动画gif,如下所示:

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

convert *.png animation.gif

这篇关于动画二次方网格变化(matshow)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆