Sean
Sean

Reputation: 51

How to plot 100% stacked bar chart

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?

Upvotes: 2

Views: 2152

Answers (2)

Erfan
Erfan

Reputation: 42916

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

Upvotes: 1

F Blanchet
F Blanchet

Reputation: 1510

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

Upvotes: 1

Related Questions