简体   繁体   中英

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())

我得到的输出

我的数据

到'tdy',工作得很好!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM