根据海洋热图的条件更改颜色

时间:2020-06-23 09:39:06

标签: python seaborn heatmap

我用以下代码生成了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,而其他单元格应保持红色到黄色的调色板。有没有简单的方法来实现这一目标?预先谢谢你!

1 个答案:

答案 0 :(得分:3)

您可以使用蓝色颜色图再次绘制热图,省去注释,并设置遮罩以仅绘制大于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()

resulting plot