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


