Python:动画改变2D numpy数组的colormap

时间:2017-04-30 21:14:05

标签: arrays numpy animation

我有一个2D numpy数组(名为enviro_grid),其中每个循环迭代都会有零,一和二。我想为更改的色彩映射的迭代设置动画,以便我可以在视觉上验证/演示所有代理都遵循我期望的行为。

代码的骨架轮廓:

import numpy as np
import random
import pylab as plt

#...initialize values, setup, seed grid with 0's, 1's, 2's, etc...

for t_weeks in range(time_limit):

    for j in range(player_n):

    #...Here lie a bunch of for/if loops which shuffle values around via rules...
    #...culminating in grid/array updates via the following line...
    #...which is seen a few times per iteration as the P[:,j]'s change.
    #...Note that P[6, j] and P[7, j] are just x, y array locations for each agent...
    #...while P[0, j] is just a designation of 1 or 2

        enviro_grid[int( P[6, j] ), int( P[7, j] )] = int( P[0, j] )

    #...Then I have this, which I don't really understand so much as...
    #... just copy/pasted from somewhere

    im = plt.imshow(enviro_grid, cmap = 'hot')
    plt.colorbar(im, orientation='horizontal')
    plt.show()

我已经查看了一些已经提供帮助的链接;例如,这些

How to animate the colorbar in matplotlib

Colormap issue using animation in matplotlib

http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

但是我太过于联盟了:Python要理解我所看到的一半,更不用说我自己的代码了。只是为了帮助说明我可能需要使用的那种非常基本的帮助,我过去完成的绘图更多的是形式图(x,y,选项)和任何动画I&#39 ;完成只是循环迭代期间绘图的自然副产品。所有这些fig.method和plt.method的东西,最终plt.show()的最终,混淆和激怒了我。在所有上述例子中使用def()函数进一步加剧了我对于将行转换到我自己的上下文时的不清晰性。

有人会介意根据我的代码为此提供有效的解决方案吗?如果需要,我可以提供更多详细信息,但我正在努力保持每个stackoverflow偏好的这个简短。

提前感谢任何人提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

在matplotlib中执行简单动画的最大挑战是理解并解决plt.show命令的阻塞行为。在this question中很好地描述了它。对于您的具体问题,也许这样的事情将是一个很好的起点:

import numpy as np
import pylab as plt

def get_data(): return np.random.randint(0,3,size=(5,5))

im = None
for _ in xrange(20):    # draw 20 frames
    if not im:
        # for the first frame generate the plot...
        im = plt.imshow(get_data(), cmap = 'hot', interpolation='none',vmin=0,vmax=2)    
        plt.colorbar(im, orientation='horizontal')
    else:
        # ... for subsequent times only update the data
        im.set_data(get_data())
    plt.draw()
    plt.pause(0.1)

请注意,您需要使用plt.pause命令为您的GUI提供足够的时间来实际绘制绘图,但您可能会缩短时间。

相关问题