Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a legend section from a seaborn plot

Using the 'tips' dataset as a toy model, I generate the following plot:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)
g = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size = 'tip',sizes=(320, 600), data=tips)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=13)
plt.show(g)

This image is exactly what I need. However, I want to remove the size = 'tip' from the legend and only keep the smoker. Essentially, remove those black circles labeled 0.0 to 12.0. How do I ensure my legend has only one variable of my choosing?

enter image description here

like image 399
JodeCharger100 Avatar asked Mar 12 '26 07:03

JodeCharger100


1 Answers

I was able to find a fix by indexing the labels in the legend.

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)
ax = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size='tip', sizes=(320, 600), data=tips)

# extract the existing handles and labels
h, l = ax.get_legend_handles_labels()

# slice the appropriate section of l and h to include in the legend
ax.legend(h[0:3], l[0:3], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=13)
plt.show()

enter image description here

like image 88
JodeCharger100 Avatar answered Mar 15 '26 14:03

JodeCharger100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!