2

Let's assume I have DataFrame as below;

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]})

I may plot the stacked graph as below:

df.groupby(['name'])['count_1', 'count_2'].sum().plot(kind='bar', stacked=True)

Plot

Then how can I make the 100% stacked bar graph? This is what I expect:
Plot2

Also could I get % number as well?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Sean
  • 51
  • 5

2 Answers2

1

You need to divide after the sum like this :

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

And to annotate :

for p in ax.patches:
    ax.annotate(str(int(p.get_height()*100))+'%', (p.get_x(), p.get_height()))
F Blanchet
  • 1,430
  • 3
  • 21
  • 32
1

First you have to manually calculate your percentages to plot them, then to get the percentages in your bars, you have to iterrate over the rows and add them with 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()

plot

Erfan
  • 40,971
  • 8
  • 66
  • 78