【问题标题】:Change color according to conditions for seaborn heatmaps根据 seaborn 热图的条件更改颜色
【发布时间】:2020-06-23 09:39:06
【问题描述】:

我使用 seaborn 生成了一个热图,代码如下:

sns.heatmap(df.sort_index(axis=1), cmap="YlOrRd_r", center=0.8, square=True, annot=annot_df.sort_index(axis=1), annot_kws={"size":22, "va": "center_baseline", "color":"white"}, fmt="", xticklabels=True, yticklabels=True, linewidth=1, linecolor="grey", vmax=1, vmin=0.5)

现在我想用不同的颜色,例如蓝色,所有值 > 0.9 的单元格,而其他的应该保留红色到黄色的调色板。有没有一种简单的方法来实现这一点?提前谢谢!

【问题讨论】:

    标签: python seaborn heatmap


    【解决方案1】:

    您可以使用蓝色颜色图再次绘制热图,省略注释并设置蒙版以仅绘制大于 0.9 的值(蒙版隐藏不需要的单元格)。

    from matplotlib import pyplot as plt
    import seaborn as sns
    import numpy as np
    
    labels = list('abcdef')
    N = len(labels)
    heatm = np.random.uniform(0.5, 1, (N, N))
    ax = sns.heatmap(heatm, cmap="YlOrRd_r", center=0.8, square=True, annot=True,
                     annot_kws={"size": 12, "va": "center_baseline", "color": "white"}, fmt=".2f", 
                     xticklabels=labels, yticklabels=labels, linewidth=1, linecolor="grey", vmin=0.5, vmax=1, cbar=False)
    ax = sns.heatmap(heatm, mask=heatm < 0.9, cmap='Blues', square=True, annot=False, vmin=0, vmax=1, cbar=False, ax=ax)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2022-07-09
      • 2015-04-06
      相关资源
      最近更新 更多