'How to get colored legend with seaborn barplot
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)
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 |