Python 向seaborn条形图添加标签

Python 向seaborn条形图添加标签,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,我试图用哈伯曼数据集() 有多少人在不同年龄段存活 在获取熊猫数据框“data”中的数据后,我采取了以下步骤。无法创建具有“%survived”的计算列。%存活=总存活数/该年龄组的总存活数 print(data.head(3)) age year nodes status 0 30 64 1 1 1 30 62 3 1 2 30 65 0 1 data['age group']

我试图用哈伯曼数据集()

  • 有多少人在不同年龄段存活
在获取熊猫数据框“data”中的数据后,我采取了以下步骤。无法创建具有“%survived”的计算列。%存活=总存活数/该年龄组的总存活数

print(data.head(3))

   age  year  nodes  status
0   30    64      1       1
1   30    62      3       1
2   30    65      0       1

data['age group'] = pd.cut(data.age,range(25,85,5))

table = data.pivot_table(index =['age group'], columns = ['status'], values='year',aggfunc=np.count_nonzero).fillna(0)
table.reset_index(level=0, inplace=True)

table['surv_pc'] = table.iloc[:,1]/(table.iloc[:,1]+table.iloc[:,2])*100

sns.set_theme(style="whitegrid")
bar = sns.barplot(data=table, x='age group',y='surv_pc')

图形类型为
matplotlib.axes.\u subplot.AxesSubplot

如何访问条形图高度,以便按照plot.text()方法放置标签? 根据
,它仅返回
对象。请帮助理解…

通过对@ForceBru提出的另一个问题的研究,我了解到所有matlplot对象都有类“patches”,其中包含图形内容。阅读更多

为了进行实验,我尝试遍历这些补丁

for bars in bar.patches:
    print(bars)

Rectangle(xy=(-0.4, 0), width=0.8, height=100, angle=0)
Rectangle(xy=(0.6, 0), width=0.8, height=84.6, angle=0)
Rectangle(xy=(1.6, 0), width=0.8, height=92.6, angle=0)
Rectangle(xy=(2.6, 0), width=0.8, height=67.4, angle=0)
Rectangle(xy=(3.6, 0), width=0.8, height=70.2, angle=0)
...
...
然后我做了实际的实现,如:
(请参阅)

我得到的图表如下


我试图查看条形图元素内部,但这会导致错误--->对于条形图中的元素:打印(元素)类型错误:“AxesSubplot”对象不是iterableHere是一些类似的问题:,谢谢,明白了!
for bars in bar.patches:
    bar.text(bars.get_x(),bars.get_height(),bars.get_height())