如何为热图的不同行使用不同的颜色贴图

2024-09-25 10:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将热图中的一行更改为其他颜色

以下是数据集:

m = np.array([[ 0.7,  1.4,  0.2,  1.5,  1.7,  1.2,  1.5,  2.5],
              [ 1.1,  2.5,  0.4,  1.7,  2. ,  2.4,  2. ,  3.2],
              [ 0.9,  4.4,  0.7,  2.3,  1.6,  2.3,  2.6,  3.3],
              [ 0.8,  2.1,  0.2,  1.8,  2.3,  1.9,  2. ,  2.9],
              [ 0.9,  1.3,  0.8,  2.2,  1.8,  2.2,  1.7,  2.8],
              [ 0.7,  0.9,  0.4,  1.8,  1.4,  2.1,  1.7,  2.9],
              [ 1.2,  0.9,  0.4,  2.1,  1.3,  1.2,  1.9,  2.4],
              [ 6.3, 13.5,  3.1, 13.4, 12.1, 13.3, 13.4, 20. ]])
data = pd.DataFrame(data = m)

现在我正在使用seaborn热图,我只能创建如下内容:

cmap = sns.diverging_palette(240, 10, as_cmap = True)
sns.heatmap(data, annot = True, cmap = "Reds")
plt.show

enter image description here

我希望更改最后一行的配色方案,以下是我想要实现的目标(我在Excel中完成了此操作):

enter image description here

我可以用Python和seaborn heatmap实现这一点吗?谢谢大家!


Tags: 数据true内容dataframedata颜色npseaborn
1条回答
网友
1楼 · 发布于 2024-09-25 10:33:45

可以一分为二,遮罩不需要的部分,然后分别打印:

# Reds
data1 = data.copy()
data1.loc[7] = float('nan')
ax = sns.heatmap(data1, annot=True, cmap="Reds")

# Greens
data2 = data.copy()
data2.loc[:6] = float('nan')
sns.heatmap(data2, annot=True, cmap="Greens")

输出:

two colors heatmap

NB。您需要根据实际的索引名调整loc[…]参数

相关问题 更多 >