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?
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")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With