【发布时间】:2021-10-04 16:05:16
【问题描述】:
我想实现一个矩阵的彩色图。这种情节的规则是:
- 如果 -5 my_matrix[i,j]
- 如果 8 my_matrix[i,j]
- 如果 20 my_matrix[i,j]
- 如果
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 的值。
【问题讨论】:
标签: python-3.x matplotlib plot colorbar colormap