Grouped bar chart for python data frame

Question:

I am trying to make a grouped bar chart in python for a dataframe that looks like this:

age sex target
25 m 0
33 f 0
20 m 1
37 f 1
40 f 1

[this is what I want it to look like. One chart for sex and another chart for age. ][1]
[1]: https://i.stack.imgur.com/NgFUE.jpg

This is what I’ve tried so far but it didn’t return what I wanted:

df.groupby('sex')[target].value_counts().plot.bar(legend=True)

Thanks.

Asked By: Ihavequestions

||

Answers:

The value_counts() alone will not suffice, you will need to unstack() it as well. Below is the updated code.

df=pd.DataFrame({'age':[25,33,20,37,40], 'sex':['m','f','m','f','f'], 'target':[0,0,1,1,1]})
ax=df.groupby('sex')['target'].value_counts().unstack().plot.bar(legend=True, rot=0)
ax.set_yticks([0,1,2])

Plot

enter image description here

Answered By: Redox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.