python - 计算直方图中每个 bin 的百分比
问题描述
我有一个看起来像这样的情节
我想找到每个 bin 的活动与非活动百分比。我希望 y 轴为 100%,并且对于每个箱,该箱中活跃与不活跃的患者百分比是多少。
这是我用来获取此图的代码:
sns.distplot(inactive['inactivity_percentage'], kde = False, label="inactive")
plt.legend(labels=['active','inactive'])
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
我尝试计算数据本身的百分比,但由于它是一个连续变量,我无法让图表看起来正确。在现有图表中,我可以获得每个 bin 的百分比吗?
解决方案
用于numpy.histogram
计算具有相同网格间距的活动和非活动计数。然后计算每个箱中的比率,并使用条形图
np.random.seed(0)
data1 = np.random.normal(loc=0.5, scale=0.25, size=(2000,))
data2 = np.random.normal(loc=0.75, scale=0.1, size=(500,))
bins,step = np.linspace(0,1,11, retstep=True)
hist1,_ = np.histogram(data1, bins=bins)
hist2,_ = np.histogram(data2, bins=bins)
prop1 = 100*hist1/(hist1+hist2)
prop2 = 100*hist2/(hist1+hist2)
fig, ax = plt.subplots()
ax.bar(x=bins[:-1], height=prop1, bottom=0, align='edge', width=step)
ax.bar(x=bins[:-1], height=prop2, bottom=prop1, align='edge', width=step)
ax.yaxis.set_major_formatter(matplotlib.ticker.PercentFormatter())
推荐阅读
- android - SupportMapFragment 正在隐藏 admob 横幅
- android - Android - 即使设备处于打盹模式,音乐应用程序如何继续在网络上流式传输?
- javascript - 遇到两个孩子用同一个钥匙。密钥应该是唯一的,以便组件在更新时保持其身份
- python - Python:如何找到一个非常大的数的质因数?
- python - 如何在python Django项目中全局设置常量
- php - 使用 PHP 删除具有空子数组的多维数组
- android - 'if' 条件在 BaseAdapter 中无法正常工作
- javascript - AWS - 您提供的 AWS 访问密钥 ID 在我们的记录中不存在错误
- python-3.x - odoo 从代码向用户发送消息(通知)
- php - AJAX 数据捕获