Python 为pcolormesh获取正确的颜色

Python 为pcolormesh获取正确的颜色,python,matplotlib,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(colou

我正在使用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.zero(xx.shape)
我应该看到所有的东西都是蓝色的,
Z=numpy.one(xx.shape)
我应该看到绿色的,
Z=2*numpy.one(xx.shape)
我应该看到红色的,或者我是这么想的。相反,我总是看到蓝色。 如果我添加这些行:

  Z[0] = 0
  Z[1] = 1
  Z[2] = 2
一切正常。它看起来好像没有所有可能的结果(0,1,2),然后它默认只使用第一种颜色,蓝色,即使结果都是2,我想要红色


我怎样才能强制它拥有我想要的颜色,即蓝色代表0,绿色代表1,红色代表2,在任何情况下?

您可以使用
clim
来修复您的色条

plt.clim(0, 3)

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

您必须规范化颜色映射:

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

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]]

虽然我最终使用了clim,但这两个伟大的答案都值得+1。