python - 使用 matshow 时 matplotlib 中的自定义颜色

标签 python matplotlib

在使用 matplotlib 时,是否有一种简单的方法可以为给定矩阵的每个元素指示特定颜色。例如,假设我们想用三种特定颜色显示“x”:红色、黑色和白色:

enter image description here

但是,我发现的唯一选择是使用“cmap”,它不会直接为您提供“直接”指定颜色的选项。

fig = plt.figure()
ax = fig.add_subplot(111)
x= [[0,0,0,0,0,0],[0,0,0,0,0,0], [0,1,1,2,1,1], [0,0,0,0,0,1], [0,1,1,1,1,1]]    
cax = ax.matshow(x,cmap=plt.cm.gray_r )
plt.show()

enter image description here

我的问题:我应该如何更改我的代码以显示上面的红/黑/白网格? [例如 0 表示黑色,1 表示白色,2 表示红色],一般来说,我们如何才能为更大的颜色列表做到这一点?像 10-15 种颜色。

另外,如何给矩阵中的某个元素指定某种颜色?例如在上面,x[i][j] == 0 then color ='black' 或者 x[i][j] == 2 then color ='red'

谢谢。

最佳答案

您可以创建自己的颜色图:

from matplotlib.colors import ListedColormap

cmap = ListedColormap(['k', 'w', 'r'])
cax = ax.matshow(x,cmap=cmap)

enter image description here

如果您想指定 10-15 种颜色,您可能会用完单字母颜色。在这种情况下,您可以指定 RGB 三元组(例如 ListedColormap([[0, 0, 0], [1, 1, 1], [1, 0, 0]]))或其他各种 color formats .或者,使用 here 列出的预定义离散(“定性”)颜色图之一。

如果矩阵中的值不是连续的整数,您可以在绘图前转换它们。

import numpy as np

x = np.array([[0,0,0,0,0,0],[0,77,0,0,22,0], [0,1,1,2,1,1], [0,0,14,0,0,1], [0,1,1,1,1,1]])
u, i = np.unique(x, return_inverse=True)
y = i.reshape(x.shape)
# array([[0, 0, 0, 0, 0, 0],
#        [0, 5, 0, 0, 4, 0],
#        [0, 1, 1, 2, 1, 1],
#        [0, 0, 3, 0, 0, 1],
#        [0, 1, 1, 1, 1, 1]])

关于python - 使用 matshow 时 matplotlib 中的自定义颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905654/

相关文章:

python - 如何 pickle Keras 模型?

python - 将一层权重从一个 Huggingface BERT 模型复制到另一个模型

python - matlibplot - 网络字节 y 轴到人类可读

python-2.7 - 如何从 matplotlib.pyplot 图中的 y 刻度标签中删除负号?

python - Pandas 数据框 : plot colors by column name

Python:生成包含反馈机制的模块图

python - 使用 savefig 的 Matplotlib 多处理字体损坏

python - python如何处理线程锁定/上下文切换?

Python Pygame 窗口没有响应

python - sunburnt - 如何查看生成的查询 URL