python - 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
解决方案
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:
or
df.unstack().plot.bar(stacked=False)
Which gives:
and for horizontal bar use barh() e.g.:
df.unstack().plot.barh(stacked=False)
推荐阅读
- php - 如何将客户用户名添加到 WooCommerce 订单号?
- azure - 存储帐户中静态网站的“请求的内容不存在”间歇性错误
- codenameone - 如何在 FontImage 上设置边距和填充?
- mysql - 排除基于多个条件的记录,在两列中具有特定值
- macos - 在 OSX 中打开选项卡时如何防止 Chrome 窃取焦点
- javascript - 如何通过单击单选按钮来切换标签的类。需要香草 JS 而不是 JQuery
- python - 无法在 python 中加载 json 对象,得到 AttributeError: 'Response' object has no attribute 'loads'
- ios - 允许点击通过 UITapGestureRecognizer 并到达下面的表格视图
- testing - 有没有办法在 TestCafe 测试中定义步骤?
- unity3d - 我应该将 Unity 库文件夹推送到 Github