如何为Matplotlib颜色映射中的单个方块指定自定义颜色?
给matshow中的单个方块设置自定义颜色
matplotlib的matshow没有直接的setcolor方法,但可以通过两种方式实现你要的效果:
方法一:修改QuadMesh的面颜色
matshow返回的是QuadMesh对象,我们可以直接修改它的facecolors属性来指定单个方块的颜色:
import matplotlib.pyplot as plt import numpy as np # 示例矩阵(根据你的需求设为5行4列) quality_matrix = np.random.rand(5, 4) fig, ax = plt.subplots() # 保存matshow返回的网格对象 mesh = ax.matshow(quality_matrix, cmap=plt.cm.Blues) # 添加单元格文本(保持你原来的逻辑) for i in range(len(quality_matrix)): for j in range(len(quality_matrix[0])): ax.text(j, i, str(quality_matrix[i][j]), va='center', ha='center') # 获取所有方块的颜色数组 face_colors = mesh.get_facecolors() cols_num = quality_matrix.shape[1] # 计算对应位置的索引并设置颜色(RGBA格式) face_colors[0 * cols_num + 2] = (0, 0, 0, 1) # (0,2)设为黑色 face_colors[1 * cols_num + 1] = (0, 0, 0, 1) # (1,1)设为黑色 face_colors[2 * cols_num + 0] = (0, 0, 0, 1) # (2,0)设为黑色 face_colors[4 * cols_num + 3] = (1, 0, 0, 1) # (4,3)设为红色 # 更新网格颜色 mesh.set_facecolors(face_colors) plt.show()
注意:索引计算规则是行号 × 列数 + 列号,因为facecolors是按行优先的一维数组存储的。
方法二:添加矩形覆盖方块
如果你想要更接近你设想的setcolor函数写法,可以封装一个函数,通过添加矩形覆盖目标方块:
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle quality_matrix = np.random.rand(5, 4) fig, ax = plt.subplots() ax.matshow(quality_matrix, cmap=plt.cm.Blues) # 添加文本时设置zorder,确保文本显示在矩形上方 for i in range(len(quality_matrix)): for j in range(len(quality_matrix[0])): ax.text(j, i, str(quality_matrix[i][j]), va='center', ha='center', zorder=2) # 封装你想要的setcolor函数 def setcolor(ax, row, col, color): # 矩形左下角坐标为(col-0.5, row-0.5),宽高均为1 rect = Rectangle((col - 0.5, row - 0.5), 1, 1, color=color, zorder=1) ax.add_patch(rect) # 调用函数设置颜色 setcolor(ax, 0, 2, 'black') setcolor(ax, 1, 1, 'black') setcolor(ax, 2, 0, 'black') setcolor(ax, 4, 3, 'red') plt.show()
这种方式更直观,但需要注意设置zorder,保证文本不会被矩形遮挡。
内容的提问来源于stack exchange,提问作者sg_rs
相关产品推荐
相关产品推荐

