如何在seaborn热力图中为掩码单元格分配自定义颜色?

7

我有一个数据集,其中的数值范围是-4到4,还有一些nan值。我使用seaborn heatmap绘制热力图。我需要使用从红色到白色再到蓝色的colormap。我的问题是遮罩单元格也是白色/灰色,这很难区分与colormap中接近0的值。

有没有办法在不重复绘制热力图的情况下将nan值分配为黑色?

2个回答

9

你有两个选项。

  1. Use the bad value of the colormap. I.e. if masked values are set to nan, they would be shown in the color set to the colormap via

    colormap.set_bad("black") 
    
  2. Make the background of the axes black, such that values which are masked and hence not plotted appear as transparent with the background color see through,

    ax.set_facecolor("black")
    

即使我使用 seaborn 调色板库中的调色板,我是否仍然可以设置错误的值? - Yusuf Talha Tamer
1
你需要一个matplotlib colormap,但是seaborn也可以使用matplotlib colormaps,所以如果不能直接使用,转换应该很简单。 - ImportanceOfBeingErnest
感谢 @ImportanceOfBeingErnest - Yusuf Talha Tamer
@ImportanceOfBeingErnest,你能告诉我如何将matplotlib的调色板转换为seaborn吗? - Jingnan Jia

1
  • .cm.get_cmapmatplotlib 3.7中已被弃用
    • 请改用mpl.colormaps['viridis']mpl.colormaps.get_cmap('viridis')
import seaborn as sns
import numpy as np
import matplotlib as mpl

np.random.seed(2023)
matrix = np.random.random_sample(size=(10, 10)) - 0.5

mask = np.where(np.logical_or(matrix >= 0.2, matrix <= -0.2), True, False)

cmap = mpl.colormaps.get_cmap('viridis')
cmap.set_bad("k")

sns.heatmap(matrix, cmap=cmap, mask=mask)

enter image description here


这里是一个完整的例子:

import matplotlib as mpl
import seaborn as sns
cmap = mpl.cm.get_cmap('gray_r')
cmap.set_bad("white")
sns.heatmap(..., cmap=cmap)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接