'How to get colored legend with seaborn barplot

There is a problem with plt.legend in seaborn and matplotlib. What is wrong with it? I can't see the legend color.

plt.figure(figsize=(30,10))
plt.xticks(rotation='85')
sns.barplot(x='label',y='cnt',data=group_label)
plt.legend(group_label['class'].unique())

The output I am getting

My data

to 'tdy', working well!



Solution 1:[1]

Instead of using matplotlib's plt.legend, just use seaborn's hue parameter. Also, in your case you want each bar to take the full width, so disable the dodge behavior as well:

sns.barplot(data=df, x='label', y='cnt', hue='class', dodge=False)
#                                        ---          -----

Full example:

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

# random data
n = 100
df = pd.DataFrame({'class': np.random.choice(['bottle', 'cable', 'leather', 'pill', 'zipper'], size=n), 'cnt': np.random.randint(80, size=n)}).sort_values('class')
df['label'] = df['class'] + df.index.astype(str)

# barplot using hue and dodge
plt.figure(figsize=(20, 5))
sns.barplot(data=df, x='label', y='cnt', hue='class', dodge=False)
plt.xticks(rotation=90)

output

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tdy