0

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.

user11305439
  • 117
  • 9
  • Possible duplicate of [Pandas - Plotting a stacked Bar Chart](https://stackoverflow.com/questions/23415500/pandas-plotting-a-stacked-bar-chart) – Alex May 01 '19 at 09:35
  • 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 May 01 '19 at 09:46
  • So another attempt (that didn't work) DF.groupby(['name', 'measure']).size().unstack().plot(kind='bar', stacked=True) – user11305439 May 01 '19 at 09:53

1 Answers1

0

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

Alex
  • 6,610
  • 3
  • 20
  • 38
  • Hi Alex, yes thats perfect. I do notice that each bar chart column goes in ascending order. Is it possible to have them in the same order that there appear in the DF? i.e. for the stacked column AA6, the values would be 3.2, 5.6, 8.8 and 2.1? – user11305439 May 01 '19 at 10:52
  • So if the size is maintained by sum(), is it unstack that decomposed into the constituents? – user11305439 May 01 '19 at 10:55