user11305439
user11305439

Reputation: 117

Creating a Stacked Bar Chart using Groups (and sum)

This is unique as I want the stacked bar chart to reflect the actual numeric value, not counts or size as per examples

I have a dataframe

## create Data frame
DF = pd.DataFrame({ 'name': 
['AA6','B7Y','CCY','AA6','B7Y','CCY','AA6','B7Y','CCY','AA6'],
                    'measure': [3.2,4.2,6.8,5.6,3.1,4.8,8.8,3.0,1.9,2.1]})

I want to groupby name

#Create a groupby object
gb=DF.groupby(['name', 'measure'])
gb.aggregate('sum')

enter image description here

And then plot a bar chart of the three categories in name(AA6, B7Y & CCY) with each of the corresponding 'measure' values stacked, and in the order they are in (not in ascending order that they appear above)

I have tried this:

DF.groupby('name').plot(kind='bar', stacked=True)

But it just creates separate plots.

Upvotes: 0

Views: 2006

Answers (1)

Alex
Alex

Reputation: 7075

If I understand what you are asking:

df = pd.DataFrame({ 'name': ['AA6','B7Y','CCY','AA6','B7Y','CCY','AA6','B7Y','CCY','AA6'],
                    'measure': [3.2,4.2,6.8,5.6,3.1,4.8,8.8,3.0,1.9,2.1]})

df.groupby(["name", "measure"])["measure"].sum().unstack().plot(kind="bar", stacked=True)

Stacked bar plot of dataframe values

We are using sum to maintain the measure size in the bar plot.
If you don't need the legend, add legend=False to the plot(...).

enter image description here

Upvotes: 0

Related Questions