假设我的DataFrame如下;
df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})
我可以如下绘制堆积图:
df.groupby(['name'])['count_1', 'count_2'].sum().plot(kind='bar', stacked=True)
然后如何制作100%堆叠的条形图?这就是我的期望:
Plot2
我还能得到%的数字吗?
答案 0 :(得分:1)
您需要像这样除以总和:
df = pd.DataFrame(df.groupby(['name'])['count_1', 'count_2'].sum())
df = df.divide(df.sum(axis=1), axis=0)
ax = df.plot(kind='bar', stacked=True, title='100 % stacked area chart')
并进行注释:
for p in ax.patches:
ax.annotate(str(int(p.get_height()*100))+'%', (p.get_x(), p.get_height()))
答案 1 :(得分:1)
首先,您必须手动计算百分比以绘制它们,然后才能获得条形图中的百分比,您必须遍历行并用plt.text
添加它们:
dfg = df.groupby('name').sum()
data = dfg.div(dfg.sum(axis=1), axis=0).mul(100)
data.plot(kind='bar', stacked=True, figsize=(15,9), title='Stacked bar')
for i, v in data.reset_index(drop=True).iterrows():
for val in v:
plt.text(i, val/2, str(round(val))+'%', size=12)
plt.show()