python – 将离散值映射到颜色

我试图基于4个离散值1,2,3,4创建pcolor.我想将1定义为黑色,2定义为红色,3定义为黄色,4定义为绿色.有谁知道怎么做?

test = ([1,2,2,1,3],[1,1,1,1,4],[2,1,1,2,1])
import numpy as np

dataset = np.array(test)
plt.pcolor(dataset)

谢谢,

最佳答案 我认为你不想使用pcolor.
From the Matlab docs(可能是matplotlib pcolor做同样的事情):

The minimum and maximum elements of C are assigned the first and last colors in the colormap. Colors for the remaining elements in C are determined by a linear mapping from value to colormap element.

您可以尝试使用imshow,并使用dict来映射您想要的颜色:

colordict = {1:(0,0,0),2:(1,0,0),3:(1,1,0),4:(0,1,0)}
test = ([1,2,2,1,3],[1,1,1,1,4],[2,1,1,2,1])
test_rgb = [[colordict[i] for i in row] for row in test]
plt.imshow(test_rgb, interpolation = 'none')
点赞