【问题标题】:Seaborn.heatmap doesn't adjust colors based on specific valueSeaborn.heatmap 不会根据特定值调整颜色
【发布时间】:2021-08-03 08:09:51
【问题描述】:

我想要一个混淆矩阵的热图,它根据每个类的百分比生成颜色。例如,最高百分比变为黑色,而其他百分比则根据其百分比变浅(较高的百分比 = 较深的颜色)。我尝试更改 vminvmax,但颜色会根据“计数”值而不是 grouped_percentages 更改。

categories = ['a', 'b', 'c']
group_percentages = []
counts = []
for i in range (len(cf)):
  for j in range(len(cf)):
    group_percentages.append(cf[j,i]/np.sum(cf[:,i]))
    counts.append(cf[j,i])

group_percentages = ['{0:.2%}'.format(value) for value in
                group_percentages]

counts = ['{0:0.0f}'.format(value) for value in
            counts]
labels = [f'{v1}\n{v2}' for v1, v2 in zip(group_percentages, counts)]
labels = np.asarray(labels).reshape(3,3,order='F')

sns.heatmap(cf, annot=labels, fmt='', xticklabels=categories, yticklabels=categories, cmap='Greys', vmax=100, cbar=False)

输出:

如您所见,尽管我将 vmax 设置为 100,cf[0,0] 为 100%,但热图中的颜色为灰色,但 cf[1,1] 为 89%,其颜色为黑色。

【问题讨论】:

标签: python matplotlib seaborn data-visualization heatmap


【解决方案1】:

您应该使用group_percentages 作为热图的数据,但首先您需要在 3x3 矩阵中重塑此列表:

percentages_matrix = np.reshape(group_percentages, (3, 3))

完整代码

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

cf = np.array([[23, 0, 3],
               [0, 106, 5],
               [0, 12, 76]])

categories = ['a', 'b', 'c']
group_percentages = []
counts = []
for i in range(len(cf)):
    for j in range(len(cf)):
        group_percentages.append(cf[j, i]/np.sum(cf[:, i]))
        counts.append(cf[j, i])

percentages_matrix = np.reshape(group_percentages, (3, 3))
group_percentages = ['{0:.2%}'.format(value) for value in group_percentages]

labels = [f'{v1}\n{v2}' for v1, v2 in zip(group_percentages, counts)]
labels = np.asarray(labels).reshape(3, 3, order = 'F')

sns.heatmap(percentages_matrix, annot = labels, fmt = '', xticklabels = categories, yticklabels = categories, cmap = 'Greys', vmax = 1, vmin = 0, cbar = False)

plt.show()

【讨论】:

    猜你喜欢
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2020-11-13
    • 1970-01-01
    • 2022-01-12
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多