[英]How to plot an array of 0/1 using matplotlib
I'm given an input of 1/0 matrix.我得到一个 1/0 矩阵的输入。 And i want to plot it to look like that: example
我想 plot 它看起来像这样:示例
The thing is that i have to color all the zeros in blue.问题是我必须把所有的零都涂成蓝色。 but when given a matrix of only ones it also turns into blue.
但是当给定一个只有一个的矩阵时,它也会变成蓝色。 is there a way to make the color "stick" with a specific number?
有没有办法让颜色“粘”到特定的数字?
the code i've used:我使用的代码:
cmap = ListedColormap(['b', 'g'])
matrix=np.array(matrix,dtype=np.uint8)
plt.imshow(matrix,cmap=cmap)
You could specify the default number of entries in the colormap using the ListedColormap
method as you thought, just set the optional argument N = 2
.您可以按照您的想法使用
ListedColormap
方法指定颜色图中的默认条目数,只需设置可选参数N = 2
。 Also, define the minimum and maximum values for your data in the imshow
method with vmin
and vmax
.此外,在
imshow
方法中使用vmin
和vmax
定义数据的最小值和最大值。
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
# Random matrix
data_ones = np.random.randint(1, 2, size=(8, 8))
data_both = np.random.randint(0, 2, size=(8, 8))
# Define colormap
cmapmine = ListedColormap(['b', 'w'], N=2)
# Plot matrix
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(data_ones, cmap=cmapmine, vmin=0, vmax=1)
ax1.set_title('Ones')
ax2.imshow(data_both, cmap=cmapmine, vmin=0, vmax=1)
ax2.set_title('Zeros and Ones')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.