4

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

2 Answers2

5

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")    
lys
  • 949
  • 2
  • 9
  • 33
4

I think you are over-complicating things with the groupby. You can use sns.countplot:

customer = pd.DataFrame({'gender':np.random.choice(["Male","Female"],100)})
sns.countplot(x='gender',hue='gender',data=customer,dodge=False)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72