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

标签 python numpy matplotlib scipy colormap

我正在寻找在 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)

产生

image

关于python - 使用 numpy/scipy 创建一个分配给特定整数值的颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806110/

相关文章:

python - 将 Pandas 数据帧转为具有多层的长格式

python - pandas 相当于 .rda/.rdata

python - 我将如何在 GeoDjango 中编写此查询? (它是 Django 中用于地理计算的库)

python - 在 matplotlib 中围绕子图绘制边框

python - 为什么 matplotlib imshow() 和 show() 函数根据图像是作为 uint8 还是 in64 读取,以不同的配色方案显示图像?

python - 导入错误: cannot import name 'mylist' from 'mymodule'

python - 如何在所有列上使用 RobustScaler?

python - 检查 NaT 或 pandas 时间戳

python - 为坐标 x 和 y 列表找到优化位置

python - 为什么使用 FuncAnimation 绘图时点不移动?