我用pcolor从2D数组中绘制信息。但是,数组中的信息在迭代过程中发生了变化,我想动态更新颜色图,以便实时看到变化。如何以最简单的方式做到这一点?

编辑-示例:

from __future__ import division
from pylab import *
import random

n = 50 # number of iterations
x = arange(0, 10, 0.1)
y = arange(0, 10, 0.1)
T = zeros([100,100]) # 10/0.1 = 100
X,Y = meshgrid(x, y)

"""initial conditions"""
for x in range(100):
 for y in range(100):
  T[x][y] = random.random()

pcolor(X, Y, T, cmap=cm.hot, vmax=abs(T).max(), vmin=0)
colorbar()
axis([0,10,0,10])
show() # colormap of the initial array

"""main loop"""

for i in range(n):
 for x in range(100):
  for y in range(100):
   T[x][y] += 0.1 # here i do some calculations, the details are not important

 # here I want to update the color map with the new array (T)


谢谢

最佳答案

我建议使用imshowdoc):

# figure set up
fig, ax_lst = plt.subplots(2, 1)
ax_lst = ax_lst.ravel()

#fake data
data = rand(512, 512)
x = np.linspace(0, 5, 512)
X, Y = meshgrid(x, x)

data2 = np.sin(X ** 2 + Y **2)
# plot the first time#fake data

im = ax_lst[0].imshow(data, interpolation='nearest',
                            origin='bottom',
                            aspect='auto', # get rid of this to have equal aspect
                            vmin=np.min(data),
                            vmax=np.max(data),
                            cmap='jet')

cb = plt.colorbar(im)

pc = ax_lst[1].pcolor(data)
cb2 = plt.colorbar(pc)


要使用imshow更新数据,只需设置数据数组,它即可为您处理所有规范化和颜色映射:

# update_data (imshow)
im.set_data(data2)
plt.draw()


要对pcolor做同样的事情,您需要对自己进行归一化和颜色映射(并猜对行主要vs列主要是正确的):

my_cmap = plt.get_cmap('jet')
#my_nom = # you will need to scale your read data between [0, 1]
new_color = my_cmap(data2.T.ravel())
pc.update({'facecolors':new_color})

draw()

关于python - 如何在matplotlib中更新pcolor?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15992149/

10-12 18:43