python - 如何从熊猫数据框中绘制具有百分比分布的水平条形图?
问题描述
我有一个像这样的大熊猫数据框:
在:
d = {'type': ['type 1', 'type 2', 'type 2', 'type 3', 'type 1', 'type 4', 'type 5', 'type 6', 'type 6', 'type 7' ], 'value': ['yes', 'no', 'yes', 'no', 'yes', 'no', 'yes','no', 'yes', 'no']}
df = pd.DataFrame(data=d)
df
出去:
type value
0 type: 1 yes
1 type: 2 no
2 type: 2 yes
3 type: 3 no
4 type: 1 yes
5 type: 4 no
6 type: 5 yes
7 type: 6 no
8 type: 6 yes
9 type: 7 no
如何创建一个水平条形图,每个条形图中是/否值的百分比?到目前为止,我试图:
sns.barplot(x='type', y='value', data=df, orient = 'h')
但是,对于每个是/否值,我只得到没有百分比分布的条形图。如何在不拆分的情况下将其绘制在同一个栏中?例如:
在上面的示例中,yes/no 的总数位于 x 轴上。
解决方案
您可以使用pd.crosstab
来计算百分比,然后plot.barh
绘制条形图:
ax = (pd.crosstab(df['type'], df['value'], normalize='index')
.plot.barh(stacked=True, alpha=0.8)
)
输出:
有关条形图上的数字,请查看此问题。
推荐阅读
- android - 将 SNES 游戏模拟器与 Android Studio 集成?
- coq - 你能在 Coq 中通过类型签名找到函数吗?
- java - 如何使用 Junit 模拟 Builder
- javascript - Javascript 日期/时间检查错误
- python - 尝试列表操作时出现浮动对象错误
- javascript - 如何使chartjs中的点可拖动?
- ssis - 如何在 ssis 中拆分支持案例详细信息
- ios - 当我用闭包初始化属性时,为什么我可以使用 self ?
- python - Python:具有 2 个函数的多处理池
- python - python检查字符串是否是回文或不在数组中