首页 > 解决方案 > 计算直方图中每个 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 的百分比吗?

标签: pythonmatplotlibseaborn

解决方案


用于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())

在此处输入图像描述


推荐阅读