首页 > 解决方案 > Seaborn pairplot 图例不显示颜色和标签

问题描述

我正在使用 seaborn 0.11.2,但我很难看到 seaborn 配对图的传说。这是代码:除图例外,一切正常

for x in x1_categorical:
   plt.figure()
   sns.pairplot(data=x1[[x,'weight']],hue=x, palette='husl', height=4, aspect=4)
   plt.title(x)

我看不到颜色或标签。我已经尝试过这里的建议:Seaborn Pairplot Legend Not Showing Colors

我不知道,提前谢谢!

标签: pythonseaborn

解决方案


如果我理解正确,则x1_categorical包含分类列名。以 seaborn 的企鹅数据集为例,当前代码如下:

from matplotlib import pyplot as plt
import seaborn as sns

x1 = sns.load_dataset('penguins')
x1_categorical = ['species', 'island', 'sex']
for x in x1_categorical:
    g = sns.pairplot(data=x1[[x, 'body_mass_g']], hue=x, palette='husl', height=4, aspect=3)
    plt.title(x)
    plt.tight_layout()

当我尝试这个(seaborn 0.11.2)时,我得到如下图:

sns.pairplot 具有 1 个数值列和 1 个分类列

这些似乎是数字列的 kdeplots,使用分类列作为色调。不幸的是,传说是空的,也当plt.legend()被尝试过。

另一种方法是显式创建 kdeplots,例如:

from matplotlib import pyplot as plt
import seaborn as sns

x1 = sns.load_dataset('penguins')
x1_categorical = ['species', 'island', 'sex']
fig, axs = plt.subplots(ncols=1, nrows=len(x1_categorical), figsize=(12, 4*len(x1_categorical)))
for ax, x in zip(axs, x1_categorical):
    sns.kdeplot(data=x1, x='body_mass_g', hue=x, palette='husl', fill=True, common_norm=False, ax=ax)
sns.despine()

sns.kdeplots 用于不同的色调列

示例代码创建了一个大图,但如果需要,也可以创建单独的图。

另一种方法可以使用common_norm=True, multiple='stack'

sns.kdeplot 多个='堆栈'


推荐阅读