如何在matplotlib clormap中为单个方块指定自定义颜色?

wpx232ag  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(153)

如何将单个方块的颜色设置为特定的颜色?这是我所拥有的:

fig, ax = plt.subplots()
    ax.matshow(quality_matrix, cmap=plt.cm.Blues)
    for i in range(len(quality_matrix)):
        for j in range(len(quality_matrix)):
            ax.text(i, j, str(quality_matrix[j][i]), va='center', ha='center')

这是一个色彩Map表。我希望能够这样做:

ax.setcolor(0, 2, 'black')
ax.setcolor(1, 1, 'black')
ax.setcolor(2, 0, 'black')
ax.setcolor(4, 3, 'red')
plupiseo

plupiseo1#

以下方法将在指定位置绘制彩色方块:

import matplotlib.pyplot as plt
import numpy as np

def set_matshow_cell_color(ax, i, j, color):
    ax.add_patch(plt.Rectangle((i - 0.5, j - 0.5), 1, 1, color=color))

quality_matrix = np.random.rand(5, 8).round(2)
fig, ax = plt.subplots()
mat = ax.matshow(quality_matrix, cmap=plt.cm.Blues)
for i in range(quality_matrix.shape[1]):
    for j in range(quality_matrix.shape[0]):
        ax.text(i, j, str(quality_matrix[j][i]), va='center', ha='center',
                color='white' if quality_matrix[j][i] > 0.3 else 'black')

set_matshow_cell_color(ax, 0, 2, 'black')
set_matshow_cell_color(ax, 1, 1, 'black')
set_matshow_cell_color(ax, 2, 0, 'black')
set_matshow_cell_color(ax, 4, 3, 'red')

plt.show()

相关问题