根据 seaborn 热图的条件更改颜色
Change color according to conditions for seaborn heatmaps
我使用以下代码生成了 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 的单元格,而其他单元格应保留红色到黄色的调色板。有没有简单的方法来实现这个?提前致谢!
您可以使用蓝色颜色图再次绘制热图,省略注释并设置遮罩以仅绘制大于 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()
我使用以下代码生成了 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 的单元格,而其他单元格应保留红色到黄色的调色板。有没有简单的方法来实现这个?提前致谢!
您可以使用蓝色颜色图再次绘制热图,省略注释并设置遮罩以仅绘制大于 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()