You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2填充式条形图内添加数据标签?

在ggplot填充式条形图内添加数据标签的解决方案

要在你的填充式条形图内部添加数据标签,可以使用geom_text(),并配合与geom_bar()一致的位置参数来确保标签位置正确。以下是修改后的完整代码:

library(ggplot2)
library(scales) # 用于格式化百分比标签

ggplot(Retention.df, aes(x = Housing_Resident, 
                         y = ..prop.., 
                         fill = Fall_Not_Retained,
                         group = Fall_Not_Retained)) + # 指定分组以正确计算比例
  geom_bar(position = "fill", colour = "black") +
  # 添加居中的百分比数据标签
  geom_text(aes(label = percent(..prop.., accuracy = 1)),
            position = position_fill(vjust = 0.5),
            size = 5) +
  ylab("Proportion") +
  xlab('Housing_Resident') +
  theme(axis.text.y = element_text(size = 16),
        axis.text.x = element_text(size = 16),
        axis.title = element_text(size = 20),
        legend.title = element_text(size = 16), 
        legend.text = element_text(size = 16),
        strip.text.x = element_text(size = 20))

关键细节说明:

  • 将y = ..count..替换为y = ..prop..,让y轴逻辑与填充条形图的比例展示一致。
  • 必须添加group = Fall_Not_Retained,否则ggplot无法按填充分组正确计算比例。
  • position_fill(vjust = 0.5)让标签垂直居中显示在每个填充块内部。
  • 使用scales::percent()将比例格式为百分比,accuracy = 1控制保留整数位,可按需调整精度。

如果需要显示原始计数而非百分比,只需修改geom_text()的标签参数:

geom_text(aes(label = ..count..),
          position = position_fill(vjust = 0.5),
          size = 5)

内容的提问来源于stack exchange,提问作者Nhu Hoang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:25:23