如何访问 seaborn 中堆叠直方图中不同条形图的高度?

How to access the height of the different bars in a stacked histplot in seaborn?

我正在尝试找到顶部条形的 y 坐标,以便我可以在顶部添加百分比。这是我得到的代码和输出。

ax = sns.histplot(x='bmi', hue='stroke', data=df, multiple='stack', binwidth=2.5, binrange=(15,52.5))

for i in range(15):
  x= ax.patches[i+15].get_x()
  y=ax.patches[i+15].get_y()
  ax.annotate("{:.1f}%".format(bmi_perc[i]), xy=(x,y))

我试图更改补丁的索引,但它们最终都给出了底部条形的高度。

堆叠直方图的高度就是堆叠个数的高度。所以你必须添加你得到的高度以获得顶部的高度用于注释。我们准备一个空列表并将其转换为具有所有高度的数组并将其转换为段数。之后,将数组相加。注释中的数字是从频率数中获得的组成比。您可以用自己的号码替换这些。

import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame({
    "bmi":np.random.normal(30,30,1000),
    "stroke":np.random.randint(0,2,1000)
})

hist, bin_edges = np.histogram(np.random.normal(30,30,1000), bins=15, range=(15, 52.5))
bmi_perc = [round(x / sum(hist), 4) for x in hist]

g = sns.histplot(x='bmi', hue='stroke', data=df, multiple='stack', binwidth=2.5, binrange=(15,52.5))

h = []
for rectangle in g.patches:
    h.append(rectangle.get_height())
h = np.array(h).reshape(2, int(len(h)/2))
h = h[0]+h[1]

for i in range(15):
    x = g.patches[i].get_x()
    y = h[i]
    g.annotate("{:.1f}%".format(bmi_perc[i]*100), xy=(x,y+1))