首页 > 解决方案 > How can I plot a categorical feature vs categorical values in python using seaborn or matplotlib

问题描述

How can I plot a bar graph for categorical feature containing values male and female to another column containing binary values like 0 and 1 such that x axis contains the male and female whereas y axis contains the number of values of 0 and 1 corresponding to male and female on y axis.

1   Male     0
2   Male     1
3   Female   1
4   Male     0
5   Female   0 
6   Female   1
7   Female   1

标签: pythonmatplotlibseaborn

解决方案


import matplotlib.pyplot as plt
import pandas as pd
import matplotlib

df=pd.DataFrame()
#dummy data
df['Sex']=['male','male', 'male', 'female', 'female', 'male', 'female']
df['Value']=[1,1,1,0,1,0,1]

print df

df=(df.groupby(['Sex','Value'])['Sex'].count())

df.unstack().plot.bar(stacked=True)

Which gives:

stacked bar

or

df.unstack().plot.bar(stacked=False)

Which gives:

unstacked bar

and for horizontal bar use barh() e.g.:

df.unstack().plot.barh(stacked=False)

enter image description here


推荐阅读