how to put the smallest bar on top of a stacked bar chart in python

58 Views Asked by At

I have this stacked bar chart but I want to reverse it and put the smallest bars on top. Here is my code:

import pandas as pd

data = {'fields': ['LastName', 'Race', 'Email', 'MidName', 'StreetAddress', 'Phone', 'State', 'FirstName', 'Gender', 'Expiration', 'StreetAddress'],
        'Status': ['complete', 'missing', 'missing', 'complete', 'complete', 'missing', 'missing', 'complete', 'complete', 'complete', 'missing'],
        'count': [27399, 146, 24225, 26078, 27269, 59, 28, 27399, 27403, 14017, 134]}

df = pd.DataFrame(data)

dfp = df.pivot(index='Status', columns='fields', values='count')

tot = dfp.sum(axis=1)

per = dfp.div(tot, axis=0).mul(100).round(2)

ax = per.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0)
ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
ax = per.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0)
for p in ax.patches:
    width, height = p.get_width(), p.get_height()
    x, y = p.get_xy() 
    ax.text(x+width/2, 
        y+height/2, 
        '{:.0f} %'.format(height), 
        horizontalalignment='center', 
        verticalalignment='center')
    ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
1

There are 1 best solutions below

1
On

All I had to do was reverse the order of columns with [::-1] and it worked fine. It sorted ascending from bottom to top. I should specify that in my original code the columns were in ascending orders by percentage .df[df.columns[::-1]].

enter image description here