从 Seaborn 热图格式中排除一列,但保留在地图中

问题描述 投票:0回答:3

所以我的桌子看起来有点像这样:

Cl1  Cl2  Cl3  Sum
0.7  0.9  0.9  2.5
0.8  1.5  0.9  3.2
2.4  2.8  2.1  7.3

我希望热图颜色应用于第 1-3 列,但不应用于

Sum
,因为它会吸收热图中的所有汁液并使各列看起来平淡无奇。

我现在想到的就是将 Sum 值除以 100,但这会让读者感到困惑并且需要解释。

有没有办法不设置 Sum 列的格式,但保持其值不变?

一些开始的代码:

import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.random.rand(3,3), columns='Cl1 Cl2 Cl3'.split())

df['Sum'] = 0
for i in df.index:
    df['Sum'].iloc[i] = np.sum(df.iloc[i])

sns.heatmap(df, annot=True, cmap='Reds')
python data-visualization seaborn
3个回答
4
投票

使用遮罩并使用 for 循环为遮罩区域添加文本。

mask = np.zeros((3, 4))
mask[:,3] = True
ax = sns.heatmap(df, mask=mask, annot=True,
             vmin=df.values[:,:3].ravel().min(),
             vmax=df.values[:,:3].ravel().max(),
             annot_kws={"size": 20, "color":"g"})


for (j,i), label in np.ndenumerate(df.values):
    if i == 3:
        ax.text(i+0.5, j+0.5, label, 
                fontdict=dict(ha='center',  va='center',
                                         color='g', fontsize=20))


更换循环的替代方案:

mask = np.zeros((3, 4))
mask[:,3] = True
sns.heatmap(df, mask=mask)
sns.heatmap(df, alpha=0, cbar=False, annot=True, annot_kws={"size": 20, "color":"g"})

导致相同的结果


3
投票

如果您的目标只是看看它在笔记本中的样子,您也许可以使用 pandas 样式:

import pandas as pd
import seaborn as sns
import io

df = pd.read_fwf(io.StringIO("""Cl1  Cl2  Cl3  Sum
0.7  0.9  0.9  2.5
0.8  1.5  0.9  3.2
2.4  2.8  2.1  7.3"""))


cm = sns.light_palette("green", as_cmap=True)

df.style.background_gradient(subset=['Cl1', 'Cl2', 'Cl3'], 
                             low=0, high=3, cmap=cm)

结果:


0
投票

为了补充@SpghttCd上面的建议,该建议仅以绿色绘制文本,而不是通常的颜色(黑色或白色,取决于背景颜色),以下是如何做到这一点:

mask = np.zeros((3, 4))
mask[:,3] = True
# Plot just the colors, and the colorbar, masking the non-colored columns.
sns.heatmap(df, mask=mask)
# Plot the values for all colored columns
sns.heatmap(df, alpha=0.0, cbar=False, annot=True, mask=mask)
# Plot the values for non-colored columns (in black)
sns.heatmap(df, alpha=0.0, cbar=False, annot=True, mask=np.logical_not(mask), annot_kws={"color":"k"})

这样,您可以看到,保留具有背景颜色的单元格的文本颜色,并将没有背景颜色的单元格设置为黑色(否则它将在白色上绘制白色文本)。

您也可以使用对数颜色图来做到这一点:

mask = np.zeros((3, 4))
mask[:,3] = True
from matplotlib.colors import LogNorm
# Plot just the colors in logNorm, and the colorbar, masking the non-colored columns.
sns.heatmap(df, norm=LogNorm(), mask=mask)
# Plot the values for all colored columns
sns.heatmap(df, norm=LogNorm(), alpha=0.0, cbar=False, annot=True, mask=mask)
# Plot the values for non-colored columns (in black)
sns.heatmap(df, norm=LogNorm(), alpha=0.0, cbar=False, annot=True, mask=np.logical_not(mask), annot_kws={"color":"k"})

© www.soinside.com 2019 - 2024. All rights reserved.