问题描述
在使用 matplotlib 时,是否有一种简单的方法可以为给定矩阵的每个元素指示特定颜色.例如,假设我们想用三种特定颜色显示x",如下所示:红色、黑色和白色:
Is there an easy way to indicate a specific color for each element of a given matrix when using matplotlib. For example, assume we want to show 'x' as follow with three specific colors: red, black, and, white:
但是,我发现的唯一选项是使用cmap",它不会直接为您提供直接"指定颜色的选项.
However, the only option I found out is using "cmap" which doesn't directly give you the option to "directly" specify the colors.
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()
我的问题:如何更改代码以显示上面的红色/黑色/白色网格?[例如0表示黑色,1表示白色,2表示红色],并且一般来说我们如何处理更大的颜色列表?像10到15种颜色.
My question: how should I change my code to show the above red/black/white grid? [e.g 0 means black, 1 means white, and 2 means red] and in general how we can do it for a larger list of colors? like 10-15 colors.
另外,如何给matix中的某个元素分配某种颜色?例如,在上面的示例中,x [i] [j] == 0然后颜色='black'或x [i] [j] == 2然后颜色='red'
In addition, how to assign to a certain element in the matix a certain color? for example in above, x[i][j] == 0 then color ='black' or x[i][j] == 2 then color ='red'
谢谢.
推荐答案
您可以创建自己的颜色图:
You can create your own color maps:
from matplotlib.colors import ListedColormap
cmap = ListedColormap(['k', 'w', 'r'])
cax = ax.matshow(x,cmap=cmap)
如果要指定10至15种颜色,则可能会用完单个字母的颜色.在这种情况下,您可以指定 RGB 三元组(例如 ListedColormap([[0, 0, 0], [1, 1, 1], [1, 0, 0]])
)或其他各种颜色格式.另外,也可以使用此处列出的一种预定义的离散(定性")颜色图.
If you want to specify 10-15 colors you may run out of single-letter colors. In this case you can specify RGB triplets (e.g. ListedColormap([[0, 0, 0], [1, 1, 1], [1, 0, 0]])
) or various other color formats. Alternatively, use one of the pre-defined discrete ("qualitative") color maps listed here.
如果矩阵中的值不是连续整数,您可以在绘图前对其进行转换.
If the values in the matrix are not consecutive integers you can transform them before plotting.
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]])
这篇关于使用matshow时在matplotlib中自定义颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!