0
votes

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.

1
Unless I am missing something, I don't see how it is the same as the examples which creates bar charts on the count of the number of occurances and not take them numerically i.e. I want a bar chart with 1 stacked column having 2.1, 3.2, 5.6 and 8.8 - user11305439
So another attempt (that didn't work) DF.groupby(['name', 'measure']).size().unstack().plot(kind='bar', stacked=True) - user11305439

1 Answers

0
votes

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