我有一个大的df,我将其分组以条形图的形式绘制。 我做了这个模拟df,以显示我的意思。 (而且我创建它的过程太有趣了……)
my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my
然后我将其分组并绘制出来:my.groupby('tv-show').sum().plot(kind='bar', stacked = True)
我想要的是这样一个情节,其中电视节目的名称在图例中而不是在x轴下,并且这些节目具有不同的颜色(当然)。
答案 0 :(得分:1)
尝试使用sns:
new_df = my.groupby('tv-show').sum().reset_index()
sns.barplot(x='tv-show', y='episodes',
hue='tv-show', data=new_df)
输出:
答案 1 :(得分:0)
使用matplotlib
的另一种替代解决方案可能看起来像
import matplotlib.patches as mpatches
fig, ax = plt.subplots(figsize=(8, 6))
# Your dataframe "my" here
ax_ = my.groupby('tv-show').sum().plot(kind='bar', stacked=True, legend=False, ax=ax)
colors = ['r', 'g', 'b']
handles = []
for col, lab, patch in zip(colors, np.unique(my['tv-show']), ax_.axes.patches):
patch.set_color(col)
handles.append(mpatches.Patch(color=col, label=lab))
ax_.legend(handles=handles)
ax_.set_xticklabels([])
答案 2 :(得分:0)