使用 numpy/scipy 创建分配给特定整数值的颜色图

Create a colormap that is assigned to specific integer values with numpy/scipy

我正在寻找在 python/matplotlib 中创建特定于指定整数值并保留该整数值的颜色图的方法。这是我如何定义 matlab 颜色图的示例:

c_map = [1   1   1;...     % Integer assignment = 0 - Air - white
         0.6 1 0.8;... % Integer assignment = 1 - Water - cyan
         1 0.6 0.2];   % Integer assignment = 2 - Sediments - orange

稍后在绘图例程中由以下人员调用:

colormap(c_map);
pcolor(xvec,zvec,ColorIntegers);
shading interp, colormap, caxis([0 3]), axis ij

整数值始终保持不变(即,空气 = 0,水 = 1,沉积物 = 2)。

我已经搜索了 matplotlib 文档和堆栈,但还没有找到创建此特定样式颜色图的方法,它将相应的整数与颜色相关联。大多数问题涉及发散、喷射、居中、线性、非线性,而不是特定颜色图的一致着色。每种颜色 必须 对应于 具体 整数值。

任何帮助将不胜感激,提前致谢。

看看ListedColormap

例如,

In [103]: y
Out[103]: 
array([[1, 1, 2, 2, 2, 1, 0, 0, 0, 1, 2, 2, 2, 2, 2, 1],
       [1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 0],
       [1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 1, 0],
       [1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 3, 3, 2, 1, 0],
       [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 1],
       [1, 1, 0, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1],
       [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1],
       [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 2],
       [0, 1, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 1, 1, 2, 2],
       [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2],
       [2, 1, 1, 0, 0, 1, 2, 2, 3, 3, 3, 2, 2, 2, 2, 1],
       [2, 1, 1, 0, 1, 2, 2, 3, 3, 3, 3, 2, 1, 1, 1, 1],
       [2, 1, 1, 0, 2, 3, 3, 3, 3, 3, 2, 1, 0, 1, 1, 0]])

In [104]: c_map = [[1, 1, 1], [0.6, 1, 0.8], [1, 0.6, 0.2], [0.75, 0.25, 0.25]]

In [105]: cm = matplotlib.colors.ListedColormap(c_map)

In [106]: imshow(y, interpolation='nearest', cmap=cm)

生成