Home > Software design >  How to add legend to seaborn.scatterplot?
How to add legend to seaborn.scatterplot?

Time:01-24

I'm trying to add a legend (no hue) about sex in a scatterplot of another two factors. I have tried to pass legend parameter to sns.scatterplot() and set manually by ax.legend(handles,labels). However, the first method failed to show up a legend, and the second one raise ValueError.
Here is my current code

    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()

Here is the sample output enter image description here

Thank you so much!

CodePudding user response:

You can do so by adding a hue argument.

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() 

enter image description here

CodePudding user response:

Scatterplot returns an axes object.

Therefore, you can use the fourth way to label an axes object: label the existing plots (although it is discouraged). You can use:

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

or

ax[1].legend(['male','female')
  •  Tags:  
  • Related