Seaborn pairplot 图例不显示颜色和标签

Seaborn pairplot legend don't show colors and labels

我使用的是 seaborn 0.11.2,但我无法看到 seaborn pairplot 的图例。 这是代码:除了图例

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

我看不到颜色和标签。我已经尝试过这里的建议:

我不知道,先谢谢了!

如果我理解正确,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)时,我得到如下图:

这些似乎是数字列的 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()

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

替代方法可以使用 common_norm=True, multiple='stack':