计算直方图中每个箱子的百分比

2024-04-25 19:17:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个情节,看起来像这样

enter image description here

我想找到每个箱子的活动与非活动百分比。我希望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()

我试图计算数据本身的百分比,但由于它是一个连续变量,我无法使图表看起来正确。在现有图表中,我可以得到每个箱子的百分比吗


Tags: 代码患者false图表plt百分比legendsns
1条回答
网友
1楼 · 发布于 2024-04-25 19:17:47

使用^{}计算具有相同网格间距的活动和非活动的计数。然后计算每个箱子中的比率,并使用条形图绘制

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

enter image description here

相关问题 更多 >

    热门问题