【问题标题】:Seaborn pairplot legend don't show colors and labelsSeaborn pairplot 图例不显示颜色和标签
【发布时间】:2021-10-21 07:02:59
【问题描述】:

我使用的是 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

我不知道,提前谢谢!

【问题讨论】:

  • 如果你写 plt.legend() 会发生什么吗?
  • 使用 plt.legend(),因为 seaborn 是使用 matplotlib 构建的,因此它会渲染得很好。
  • 没有测试数据很难猜出你想做什么。你能解释一下吗? pairplot 为数字列的组合创建图。带有图例的hue 用于分类列(例如,将hue='species' 用于虹膜数据集)。 xweight 是数字吗?使用hue=x 的含义很难理解。您希望在传说中看到什么?您可以添加其中一个地块的图像吗?另请注意,在您的代码中,plt.figure() 创建了一个空图,因为pairplot 是一个创建自己的新图形的图形级函数。
  • @avats 我试过了,但这个错误发生在我身上“没有找到带有标签的句柄放在图例中。”
  • @JohanC 感谢您的观察!x 是一个分类变量(所以是对象类型),而 weight 是一个数字。我无法添加图像,因为不幸的是我没有足够的声誉,但图表工作正常,那么为什么图表工作而不是图例?

标签: python seaborn


【解决方案1】:

如果我理解正确,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'

【讨论】:

  • 这样可以正常工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多