형한결
형한결

Reputation: 113

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!

Upvotes: 1

Views: 1558

Answers (1)

tdy
tdy

Reputation: 41327

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

Upvotes: 2

Related Questions