Search code examples
pythonlegendscatter-plot

What is the function to display a legend for a scatter plot in python?


I'm trying to show the legend but it's not coming up. There should be 4 legend items (one for each color).

You'll see there's a legend that begins with 1 letter but that's it?

I would be greatful for any help. I've been searching online for ages.

This is my code

import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from pathlib import Path
from matplotlib.lines import Line2D

#set dataframe
df = dataset

#colour dictionary
cdict = {
'Type1':2,
'Type2': 4,
'Type3':6, 
'Type4':8,
}

fig, ax = plt.subplots()
dataset.plot(kind='scatter', 
x='Delta', 
y='Class', 
c=df['FTypes'].map(cdict),
)


plt.legend('FTypes')

#fit graph layout to screen
plt.tight_layout()

#add ref line
plt.axvline(x=0)

#show plot
plt.show()

enter image description here

I've tried using ax.legend() and also plt.legend().

I may need to use handles but I'm not super familar with that yet.


Solution

  • I can't remember how to do this with matplotlib but you can easily do it with seaborn, which automatically adds legend when a categorical variable is used to add hue to points:

    import seaborn as sns
    
    fig, ax = plt.subplots()
    sns.scatterplot(df, x='Delta', y='Class', hue='FTypes', ax=ax)
    
    #fit graph layout to screen
    plt.tight_layout()
    
    #add ref line
    plt.axvline(x=0)