0

I m trying to show the number of counts in each color bar . is there a way to do that ? here is the code:

import pandas as pd

# sample data
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)

# pivot the dataframe into the wide form
dfp = df.pivot(index='Status', columns='fields', values='count')

# get the totals along the rows
tot = dfp.sum(axis=1)

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

# plot
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)

i m getting the percentages but i also want to be able to show in each box the counts - for example email in the right bar is 24225 and i want that total to be there . how do i do that ? enter image description here

vanetoj
  • 103
  • 11

1 Answers1

0

There is similar question Annotate stacked barplot matplotlib and pandas

And since the y axis has a range between (0-100) you could also use percentages (or you can just remove the percentage symbol if you don't like it). The code would look like this:

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)
A.Demiraj
  • 51
  • 5
  • I m asking if there is a way to put the count column inside the boxes not the percentage .. i know its weird but then it will be a full data picture – vanetoj Jan 23 '23 at 19:17
  • I removed the percentage symbol so that it now displays the actual count – A.Demiraj Jan 25 '23 at 10:26