带有离散 pcolormesh 的离散颜色条
discrete colorbar with discrete colormesh
我想实现矩阵的彩色绘图。这种情节的规则是:
- if -5 <
my_matrix[i,j]
< 8 使用白色。
- 如果 8 <
my_matrix[i,j]
< 20 使用黑色。
- 如果 20 <
my_matrix[i,j]
< 30 使用红色。
- if
my_matrix[i,j]
> 30 使用绿色。
这是代码,如您所见,矩阵是随机的。我还打印了一个文本图,以检查打印是否正确。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
Z_1 = 8
Z_2 = 20
Z_3 = 30
period = 5
size = 10
np.random.seed(1)
my_matrix = np.random.randint(-4,50,[period,size])
my_matrix[0,0] = 33
my_matrix[1,0] = 31
print(" ")
print(my_matrix.T)
print(" ")
bounds = [-5,Z_1,Z_2,Z_3]
cmap = colors.ListedColormap(['white', 'black','red','green' ]).with_extremes(over='green')
pm=plt.pcolormesh(my_matrix.T, cmap = cmap)
plt.colorbar(pm, boundaries = bounds ,extend = 'max', extendfrac='auto' ,ticks=bounds)
for i in range(len(my_matrix[:,0])):
for j in range(len(my_matrix[0,:])):
plt.text(i,j,str(my_matrix[i,j]), va='center_baseline', ha='left',color = 'blue')
#plt.clim(0, 31)
plt.gca().invert_yaxis()
plt.show()
我认为命令.with_extremes(over='...')
对这种情节很有用。
不幸的是,我得到以下图片。绿色不存在并且不遵守某些绑定(请参阅 my_matrix(0)(1) 或 my_matrix(1)(0))。
我想要一个具有上述规则的绘图,它在颜色条中包含所有相关颜色,同时考虑到那些大于 30 的值。
您可以使用 BoundaryNorm
来设置边界的位置。此外,您不需要在颜色列表中包含绿色作为一种颜色。例如:
bounds = [-5, Z_1, Z_2, Z_3]
cmap = colors.ListedColormap(['white', 'black', 'red']).with_extremes(over='green')
norm = colors.BoundaryNorm(bounds, cmap.N)
pm = plt.pcolormesh(my_matrix.T, cmap=cmap, norm=norm)
plt.colorbar(pm, extend='max', extendfrac='auto')
我想实现矩阵的彩色绘图。这种情节的规则是:
- if -5 <
my_matrix[i,j]
< 8 使用白色。 - 如果 8 <
my_matrix[i,j]
< 20 使用黑色。 - 如果 20 <
my_matrix[i,j]
< 30 使用红色。 - if
my_matrix[i,j]
> 30 使用绿色。
这是代码,如您所见,矩阵是随机的。我还打印了一个文本图,以检查打印是否正确。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
Z_1 = 8
Z_2 = 20
Z_3 = 30
period = 5
size = 10
np.random.seed(1)
my_matrix = np.random.randint(-4,50,[period,size])
my_matrix[0,0] = 33
my_matrix[1,0] = 31
print(" ")
print(my_matrix.T)
print(" ")
bounds = [-5,Z_1,Z_2,Z_3]
cmap = colors.ListedColormap(['white', 'black','red','green' ]).with_extremes(over='green')
pm=plt.pcolormesh(my_matrix.T, cmap = cmap)
plt.colorbar(pm, boundaries = bounds ,extend = 'max', extendfrac='auto' ,ticks=bounds)
for i in range(len(my_matrix[:,0])):
for j in range(len(my_matrix[0,:])):
plt.text(i,j,str(my_matrix[i,j]), va='center_baseline', ha='left',color = 'blue')
#plt.clim(0, 31)
plt.gca().invert_yaxis()
plt.show()
我认为命令.with_extremes(over='...')
对这种情节很有用。
不幸的是,我得到以下图片。绿色不存在并且不遵守某些绑定(请参阅 my_matrix(0)(1) 或 my_matrix(1)(0))。
我想要一个具有上述规则的绘图,它在颜色条中包含所有相关颜色,同时考虑到那些大于 30 的值。
您可以使用 BoundaryNorm
来设置边界的位置。此外,您不需要在颜色列表中包含绿色作为一种颜色。例如:
bounds = [-5, Z_1, Z_2, Z_3]
cmap = colors.ListedColormap(['white', 'black', 'red']).with_extremes(over='green')
norm = colors.BoundaryNorm(bounds, cmap.N)
pm = plt.pcolormesh(my_matrix.T, cmap=cmap, norm=norm)
plt.colorbar(pm, extend='max', extendfrac='auto')