Grouped bar plot with categorical column count

Viewed 578

I have this dataframe that has many columns, 2 of them are y and poutcome. Both of them are categorical data. I make a grouped bar plot based on y with sub bar plot poutcome. I tried to create a group by that results this

y    poutcome
no   failure      427
     other        159
     success       46
     unknown     3368
yes  failure       63
     other         38
     success       83
     unknown      337

Based on that grouped by dataframe, I thought it will result to a graph that looks like this, the legend and the colored bars will be failure,success,other and unknown and they will be grouped by yes and no (in example graph, 4 and 5 would be yes and no). You got the gist.

g1

The group by is this bank.groupby(['y','poutcome'])['poutcome'].count() But instead shows like above, mine show like this

enter image description here

How do I make it like the first graph? The bars represents the poutcome and they are grouped by y

2 Answers

You should be able to just unstack(level=1) before plotting:

grouped.unstack(level=1).plot.bar()

This is the dataframe that I used initally:

     y poutcome  count
0   no  failure    427
1   no    other    159
2   no  success     46
3   no  unknown   3368
4  yes  failure     63
5  yes    other     38
6  yes  success     83
7  yes  unknown    337

You should be able to get this from your groupby by setting as_index=False

You can then use DataFrame.pivot to arrange the values for plotting:

df.pivot(index="poutcome", columns="y", values="count")
# y           no  yes
# poutcome           
# failure    427   63
# other      159   38
# success     46   83
# unknown   3368  337

# and plot that:
df.pivot(index="poutcome", columns="y", values="count").plot.bar()

enter image description here

Alternatively to have poutcome in the legend swap the index and columns parameters:

df.pivot(index="y", columns="poutcome", values="count").plot.bar()

enter image description here

Related