在 seaborn 热力图中将数值映射到特定颜色

10

我正在使用Python中的seaborn软件包绘制热力图。 我要绘制的值是离散的,它们是整数-101

我希望带有值-1的单元格显示为绿色,带有0的单元格显示为黄色,1的单元格显示为红色。

cubehelix_palette()color_palette()函数中是否可以指定这种规则?


请参见为seaborn热力图分配特定颜色 - Trenton McKinney
1个回答

20
你可以按照以下方式使用 matplotlib.colors.ListedColormap
import numpy as np
import seaborn as sns
from matplotlib.colors import ListedColormap

data = np.random.randint(-1, 2, (10,10)) # Random [-1, 0, 1] data
sns.heatmap(data, cmap=ListedColormap(['green', 'yellow', 'red']), annot=True)

它产生以下结果:

enter image description here

您可以将字符串'green','yellow','red'替换为十六进制颜色,例如'#FF0000'(相当于'red'),或RGB颜色,例如(1.,0.,0.)(也等同于'red')。


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