繁体   English   中英

如何将图例添加到 seaborn.scatterplot?

[英]How to add legend to seaborn.scatterplot?

我有一个多列的 dataframe。 我试图在另外两个因素的散点图中添加一个关于性的图例(无色调)。 我试图将图例参数传递给 sns.scatterplot() 并由 ax.legend(handles,labels) 手动设置。 但是,第一种方法未能显示图例,第二种方法引发 ValueError。
这是我当前的代码

    bar=sns.barplot(x=df.loc[:,'Sex'],y=df.loc[:,'Salary'],ax=ax[0])
    bar.set(ylim=(10000,30000))
    sca=sns.scatterplot(data=df,x=df.loc[:,'yearsinrank'],y=df.loc[:,'Salary'],ax=ax[1])
    sca.legend(handles=df.loc[:,'Sex'],labels=['male','female'])
    sca.set(ylim=(10000,40000),xlim=(-5,30))
    plt.show()

这是样品 output 在此处输入图像描述

太感谢了!

您可以通过添加一个hue参数来做到这一点。

fig, ax = plt.subplots(1, 2, figsize=(16, 5))

bar = sns.barplot(
    x=df.loc[:, 'Sex'],
    y=df.loc[:, 'Salary'],
    ax=ax[0]
)
bar.set(ylim=(10000, 30000))
sca = sns.scatterplot(
    data=df,
    x=df.loc[:, 'yearsinrank'],
    y=df.loc[:, 'Salary'],
    hue=df.loc[:, 'Sex'], # hue argument to specify grouping variable
    ax=ax[1]
)
sca.set(ylim=(10000, 40000), xlim=(-5, 30))
plt.show() 

在此处输入图像描述

散点图返回轴 object。

因此,您可以使用第四种方式 label 一个轴 object : label 现有的情节(虽然不鼓励)。 您可以使用:

sca.legend(['male','female')

或者

ax[1].legend(['male','female')

所以我通过使用hue属性和legend setter方法解决了这个问题。 (似乎色调和图例之间有某种关系?)这是我当前的代码

f,ax = plt.subplots(nrows=1,ncols=2,sharex=False,sharey=False)
bar=sns.barplot(x=df.loc[:,'Sex'],y=df.loc[:,'Salary'],ax=ax[0])
bar.set(ylim=(10000,30000))
sca=sns.scatterplot(data=df,x=df.loc[:,'yearsinrank'],y=df.loc[:,'Salary'],ax=ax[1],hue=df.loc[:,'Sex'])
sca.legend(loc='lower right')
sca.set(ylim=(10000,40000),xlim=(-5,30))
plt.show()

这是最终的结果在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM