Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas pivot table to stacked bar chart

I'm trying to take this pivot table and create a stacked bar chart of wins and losses by battle type.

import pandas as pd
import numpy as np

np.random.seed(1)
df = pd.DataFrame({'attacker_outcome':np.random.choice(['win', 'loss'], 20, replace=True),
                'battle_type':np.random.choice(['pitched battle', 'siege', 'ambush', 'razing'], 20, replace=True)})


   attacker_outcome     battle_type
0              loss          ambush
1              loss           siege
2               win          ambush
3              loss           siege
4              loss           siege
5               win          ambush
6               win           siege
7               win          razing
8              loss           siege
9              loss          ambush
10             loss          razing
11             loss           siege
12              win          razing
13             loss          razing
14              win          ambush
15              win  pitched battle
16             loss          ambush
17             loss           siege
18              win  pitched battle
19             loss           siege

I tried to initialize a new column, groupby and count. I'm trying to create a stacked bar chart from this pivot table, and starting to get lost here. I'm getting this:

df.assign(count =1 ).groupby(['attacker_outcome', 'battle_type']).count().plot.bar(stacked=True)

barchart

Any help is appreciated!

like image 206
Matt W. Avatar asked Dec 18 '22 01:12

Matt W.


1 Answers

You can accomplish this through grouping and unstacking:

df.groupby('battle_type')['attacker_outcome']\
    .value_counts()\
    .unstack(level=1)\
    .plot.bar(stacked=True)

enter image description here

like image 190
Brad Solomon Avatar answered Dec 27 '22 01:12

Brad Solomon