【问题标题】:discrete colorbar with discrete colormesh具有离散 pcolormesh 的离散颜色条
【发布时间】: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


    【解决方案1】:

    您可以使用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')
    
    

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2022-01-02
      相关资源
      最近更新 更多