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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.