0

I plotted a scatterplot with seaborn library and I want to change the legend text but dont know how to do that.

example: The following is iris dataset with species columns encoded in 0/1/2 as per species.

plt.figure(figsize=(8,8))
pl = sns.scatterplot(x='petal_length', y ='petal_width', hue='Species', data=data, s=40,
                palette='Set1', legend='full')

enter image description here

I want to change the legends text from [0, 1, 2] to ['setosa', 'versicolor', 'virginica']. can anybody help.

1 Answer 1

4

First, Seaborn (and Matplotlib) usually picks up the labels to put into the legend for hue from the unique values of the array you provide as hue. So as a first step, check that the column Species in your dataframe actually contains the values "setosa", "versicolor", "virginica". If not, one solution is to temporarily map them to other values, for the purpose of plotting:

legend_map = {0: 'setosa',
              1: 'versicolor',
              2: 'virginica'}

plt.figure(figsize=(8,8))
ax = sns.scatterplot(x=data['petal_length'], y =data['petal_width'], hue=data['species'].map(legend_map), 
                     s=40, palette='Set1', legend='full')
plt.show()

iris dataset scatterplot

Alternatively, if you want to directly manipulate the plot information and not the underlying data, you can do by accessing the legend names directly:

plt.figure(figsize=(8,8))
ax = sns.scatterplot(x='petal_length', y ='petal_width', hue='species', data=data, s=40,
                 palette='Set1', legend='full')
l = ax.legend()
l.get_texts()[0].set_text('Species') # You can also change the legend title
l.get_texts()[1].set_text('Setosa')
l.get_texts()[2].set_text('Versicolor')
l.get_texts()[3].set_text('Virginica')
plt.show()

This methodology allows you to also change the legend title, if need be.

3
  • Thanks a lot for your answer!! I tried many other things before but didn't worked out. Commented Sep 20, 2020 at 10:11
  • what if I want to delete 0th text. how to do that. I tried to set_text('') but it leaves a blank line which I don't want. Commented Sep 20, 2020 at 10:33
  • 1
    Yeah the locations in the legend are fixed by then, so you cannot just remove it. One trick is to plot each "Species" (or category) on a separate ax, and when you get to the one you want to omit in the legend, specify label='_no_legend_'. As a shortcut, you can map that species/category to a name that starts with an understore, and by convention it will not show up in the legend: legend_map = {'setosa': '_setosa', 'versicolor': 'versicolor', 'virginica': 'virginica'}
    – tania
    Commented Sep 21, 2020 at 6:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.