为pcolormesh

时间:2016-06-04 04:03:21

标签: python matplotlib

我正在使用pcolormesh来显示我正在运行的某些算法的结果。 我为某些x_min, x_max等创建了常用的网格,并定义了我的颜色贴图

h = (x_max - x_min) / 1000.
xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, h), numpy.arange(y_min, y_max, h))
colours = ("blue", "green", "red")
cmap = colors.ListedColormap(colours)

然后执行plt.pcolormesh(xx, yy, Z, alpha=0.7, cmap=cmap),其中Z是我的预测结果(可能是任何0,1或2值,无关紧要)。

Z = numpy.zeros(xx.shape)我应该看到一切都是蓝色的,Z = numpy.ones(xx.shape)我应该看到绿色,Z = 2*numpy.ones(xx.shape)我应该看到红色,或者我认为。相反,我总是看到蓝色。 如果我添加这些行:

  Z[0] = 0
  Z[1] = 1
  Z[2] = 2

一切都按预期工作。看起来好像结果没有所有可能的结果(0,1,2)然后它默认只使用第一种颜色,蓝色,即使结果是全2,我想要红色。

我怎样才能强迫它拥有我想要的颜色,即蓝色为0,绿色为1,红色为2,

2 个答案:

答案 0 :(得分:2)

您可以使用clim修复颜色栏。

plt.clim(0, 3)

这将强制0为蓝色,1为绿色,2为红色。

答案 1 :(得分:2)

您必须规范化ColorMap:

import matplotlib.pylab as plt
import numpy as np
from matplotlib.colors import ListedColormap, BoundaryNorm

x_max = 100.
x_min = 0.
y_max = 100.
y_min = 0.
h = (x_max - x_min) / 5.
xx, yy = np.meshgrid(np.arange(x_min, x_max+h, h), np.arange(y_min, y_max+h, h))
Z = np.random.randint(3, size=(5,5))
# define color map & norm it
colours = (["blue", "green", "red"])
cmap = ListedColormap(colours)
bounds=[0,1,2,np.max(Z)+1] # discrete values of Z
norm = BoundaryNorm(bounds, cmap.N)
# for colorbar
ticks  = [.5,1.5,2.5]
labels = ['0','1','2']
# plot
pcm = plt.pcolormesh(xx, yy, Z, alpha=0.7, cmap=cmap, norm=norm)
cb = plt.colorbar(pcm, cmap=cmap, norm=norm, ticks=ticks)
cb.set_ticklabels(labels)
plt.show()

enter image description here

Z阵列:

[[0 0 1 0 0]
 [0 0 0 1 1]
 [1 0 0 0 1]
 [1 1 2 2 0]
 [1 1 1 2 2]]