2

Trying to customize the legend for my seaborn scatterplot plot with plt.legend, the text looks fine, but it keeps breaking the corresponding legend markers.

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.scatterplot(x="total_bill", y="tip", hue="day",
 data=tips, s=75,  edgecolor='k')

# title
plt.legend(title='Day of Week', labels=['Thursday', 'Friday', 'Saturday', 'Sunday'])

sns.plt.show()

The text looks fine but the dots next to each label are messed up after the first one. The first legend item is fine, it skips the marker for the second legend item, and subsequent legend items are offset.

Results here.

CAPSLOCK
  • 6,243
  • 3
  • 33
  • 56
rmc33
  • 65
  • 1
  • 5

1 Answers1

2

Based on the answers here and here, you need to access the legend object and modify the texts, which is not as straightforward in Seaborn as I thought it would be.

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.scatterplot(x="total_bill", y="tip", hue="day",
                    data=tips, s=75,  edgecolor='k')

# Assumes Seaborn 0.9.0
legend = g.legend_

# Set legend title
legend.get_texts()[0].set_text('Day of Week')

labels=['Thursday', 'Friday', 'Saturday', 'Sunday']

# Set legend labels
for i, label in enumerate(labels):
    # i+1 because i=0 is the title, and i starts at 0
    legend.get_texts()[i+1].set_text(label) 

# sns.plt.show() for me gives "AttributeError: module 'seaborn' has no attribute 'plt'"
plt.show()

final image

m13op22
  • 2,168
  • 2
  • 16
  • 35