0

I have the following table:

+-------------+--------+-----+
|       fields|  Status|count|
+-------------+--------+-----+
|     LastName|complete|27399|
|         Race| missing|  146|
|        Email| missing|24225|
|      MidName|complete|26078|
|StreetAddress|complete|27269|
|        Phone| missing|   59|
|        State| missing|   28|
|    FirstName|complete|27399|
|       Gender|complete|27403|
|   Expiration|complete|14017|
|StreetAddress| missing|  134|
+-------------+--------+-----+

And I would like to create a stacked bargraph with unique values of status on x-axis stacked by status with values from the count.

I have been played around with simple ones:

per_df.plot(kind='bar',stacked=True)

and also tried seaborn

  sns.barplot(data=data, x='fields',y='status')
  plt.tight_layout()
  plt.show()

I also tried several other ways, that I already deleted.

I also checked on the following:

How to plot a bar plot of 2 categorical columns using matplotlib or seaborn

https://pythonguides.com/stacked-bar-chart-matplotlib/

https://www.geeksforgeeks.org/plot-multiple-columns-of-pandas-dataframe-on-bar-chart-with-matplotlib/

but all of them only have one categorical variable. Thank you for the guidance

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
budding pro
  • 135
  • 1
  • 2
  • 10

1 Answers1

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

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158