0

So I was trying to change the legend from a scatterplot using seaborn and matplotlib. I'm using the iris dataset to illustrate my problem.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"

iris = pd.read_csv(url)

I wanted to move the legend to the outside of the plot area and to change the title and labels to their capitalized from. Running this code

sns.scatterplot(x="sepal_width", y="petal_width", data=iris, hue="species")
plt.legend(
    title="Species",
    labels=['Setosa', 'Versicolor', 'Virginica'],
    bbox_to_anchor = (1,1),
    loc=2)

I get this plot:

seaborn wrong label

I noticed that the "Setosa" dot was smaller than the others and was the same color as "Versicolor". So I tried adding a fourth label:

sns.scatterplot(x="sepal_width", y="petal_width", data=iris, hue="species")
plt.legend(
    title="Species",
    labels=['Setosa', 'Versicolor', 'Virginica', 'test'], 
    bbox_to_anchor = (1,1), 
    loc=2)

seaborn 4 labels

Now I believe it is plotting an additional label at the beginning and I don't now why. Anyone has an idea on how to avoid this "extra" label?

Myst
  • 25
  • 1
  • 7
  • 1
    Honestly it's easier to change the values in the dataframe. `iris.species = iris.species.str.capitalize()` and then `plt.legend(title="Species", bbox_to_anchor = (1,1), loc=2)`. See [code and plot](https://i.stack.imgur.com/oG0o5.png) – Trenton McKinney Nov 07 '21 at 16:53
  • 2
    @TrentonMcKinney you can change the title with `move_legend`; `sns.move_legend(obj, loc, title="new title)` – mwaskom Nov 07 '21 at 18:20
  • See this [answer](https://stackoverflow.com/a/68849891/7758804) for [`seaborn.move_legend`](https://seaborn.pydata.org/generated/seaborn.move_legend.html) – Trenton McKinney Nov 08 '21 at 11:01
  • This answer doesn't work for me, I don't want to change the dataset – Myst Nov 08 '21 at 19:24
  • The duplicate list has been added to and _Change legend location and labels in Seaborn scatter plot_ has been tested to do what you want – Trenton McKinney Nov 08 '21 at 21:02

0 Answers0