【问题标题】:Add Labels to seaborn barchart向 seaborn 条形图添加标签
【发布时间】:2020-12-26 02:20:04
【问题描述】:

我正在尝试在 haberman 数据集中回答 (https://www.kaggle.com/gilsousa/habermans-survival-data-set)

  • 在不同年龄段的人中存活的百分比是多少

在熊猫数据框“数据”中获取数据后,我采取了以下步骤。无法创建具有“存活百分比”的计算列。存活百分比 = 存活总数 / 该年龄组的总数。

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._subplots.AxesSubplot

如何访问条形高度,以便按照 plot.text() 方法放置标签? 根据文档 https://matplotlib.org/3.1.0/api/axes_api.html?highlight=matplotlib#matplotlib.axes.Axes,它只返回 Axes 对象。请帮助理解...

【问题讨论】:

标签: python pandas matplotlib seaborn


【解决方案1】:

从@ForceBru 提出的其他问题的研究中,我了解到所有 matlplot 对象都有包含图形内容的类“补丁”。阅读更多https://matplotlib.org/3.1.0/api/patches_api.html?highlight=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)
...
...

然后我做了实际的实现,如:
(参考here

for bars in bar.patches:
    bar.text(bars.get_x(),bars.get_height(),bars.get_height()) 

我得到了如下图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多