[英]Plot a matrix in Python with custom colors
I'm trying to plot a matrix using pytlot in python. 我正在尝试在python中使用pytlot绘制矩阵。
import matplotlib.pyplot as plt
m = [
[1, 0, 2, 0, 0],
[1, 1, 1, 2, 0],
[0, 4, 1, 0, 0],
[0, 4, 4, 1, 2],
[1, 3, 0, 0, 1],
]
plt.imshow(m)
plt.show()
This look like what I need, but the problem is that I need to be able to select the color for a position. 这看起来像我需要的,但是问题是我需要能够选择位置的颜色。
For example: 例如:
the position 1x2 has to be red. 位置1x2必须为红色。
anyway to archive this with Python and Pyplot? 无论如何用Python和Pyplot将其存档?
You can map a certain range to a certain colormap using the vmin
and vmax
arguments, and then assign those colors to particular values in your graph. 您可以使用vmin
和vmax
参数将特定范围映射到特定颜色图,然后将这些颜色分配给图形中的特定值。 Here is a simple example, using the brg
cmap . 这是一个使用brg
cmap的简单示例。
I used 1-10 as a scale, so 1 will be Blue, 5 will be Red, and 10 will be Green, etc. 我使用1-10作为比例,所以1将是蓝色,5将是红色,10将是绿色,依此类推。
import matplotlib.pyplot as plt
m = [
[1, 0, 2, 0, 0],
[1, 1, 1, 2, 0],
[0, 4, 1, 0, 0],
[0, 4, 4, 1, 2],
[1, 3, 0, 0, 1]
]
dct = {1: 5., 0: 1., 2: 1., 3: 1., 4: 1.}
n = [[dct[i] for i in j] for j in m]
print(n)
plt.imshow(n, cmap='brg', vmin=1, vmax=10)
plt.show()
Output (All 1's in your matrix are now red, all other values set to blue): 输出(矩阵中的所有1现在都是红色,所有其他值都设置为蓝色):
I guess that matplotlib.colors.ListedColormap
is what you need here: 我猜想matplotlib.colors.ListedColormap
是您在这里需要的:
import matplotlib
import matplotlib.pyplot as plt
colors = 'lime red blue magenta yellow'.split()
cmap = matplotlib.colors.ListedColormap(colors, name='colors', N=None)
m = [
[1, 0, 2, 0, 0],
[1, 1, 1, 2, 0],
[0, 4, 1, 0, 0],
[0, 4, 4, 1, 2],
[1, 3, 0, 0, 1],
]
plt.imshow(m, cmap=cmap)
plt.show()
You may also use (R,G,B) tuples (instead of predefined color strings) in your list if you need more control 如果需要更多控制,也可以在列表中使用(R,G,B)元组(而不是预定义的颜色字符串)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.