Avoiding repeated legend in seaborn boxplot overlaid by swarmplot
Asked Answered
A

1

7

enter image description here

In the seaborn based plot below, I am making a box plot overlaid by a swarm plot. Both are subset by hue. Is there any way I can not have them repeated twice in the legend though?

Here is my code:

ax = sns.boxplot(x=name_xaxis, y=name_col, hue=hue, data=frame, palette='Set2', linewidth=1.5, width=0.5)
sns.swarmplot(x=name_xaxis, y=name_col, hue=hue, data=frame, palette='Set2', color='.25', split=True)
Anabatic answered 28/3, 2016 at 17:42 Comment(0)
D
21

Try to add this after sns.swarmplot(...):

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:2], labels[:2])

This should replace the legend with only two entries from existing one.

Daiseydaisi answered 28/3, 2016 at 18:19 Comment(2)
You're a darn legend!Harpoon
I wish I could upvote this answer afresh every time I stumble upon it!Capps

© 2022 - 2024 — McMap. All rights reserved.