Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn : How to add legend to seaborn barplot

Tags:

python

seaborn

I'm trying to add legend to my seaborn bar plot. I already tried to add hue but it pops out error saying IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match). so I tried other solution by giving it labels parameter. Here's the code

plt.figure(figsize=[15,12])                     
sns.barplot(x=customer['gender'].unique(),y=customer.groupby(['gender'])['gender'].count(),
            data=customer,label=customer['gender'].unique())
plt.legend(loc="upper left")

This is the result, this result is wrong. It's supposed to have label Female and Male according to their color in the bar. The Female and Male is supposed to be separated with different colors. I already tried to follow this,this, and this but none of those work for me. How should I do it?

plot

like image 649
ImBaldingPleaseHelp Avatar asked Oct 15 '25 13:10

ImBaldingPleaseHelp


1 Answers

Here's a one liner you can use in your existing code by setting the handles param for the legend:

patches = [matplotlib.patches.Patch(color=sns.color_palette()[i], label=t) for i,t in enumerate(t.get_text() for t in plot.get_xticklabels())]

Use like this:

plt.legend(handles=patches, loc="upper left") 

plot

Full script:

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
import numpy as np
import random

#generate random test data
genders = ['Male', 'Female']
sampling = random.choices(genders, k=100)
customer = pd.DataFrame({'gender': sampling})

#you can change the palette and it will still work
sns.set_palette("Accent")
                  
plot = sns.barplot(x=customer['gender'].unique(),y=customer.groupby(['gender'])['gender'].count(),
            data=customer) 

patches = [matplotlib.patches.Patch(color=sns.color_palette()[i], label=t) for i,t in enumerate(t.get_text() for t in plot.get_xticklabels())]
plt.legend(handles=patches, loc="upper left")    
like image 133
lys Avatar answered Oct 18 '25 15:10

lys