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

如何在R ggplot比例条形图上添加展示实际数量而非占比的标签

你可以直接用geom_text()层实现需求,只需将文本的位置参数设置为和条形层一致的堆叠填充模式,同时直接将原始amount字段映射为标签即可,不需要转换为比例值。

完整可运行代码如下:

library(ggplot2)
df <- data.frame(speech = c("figurative", "literal", "figurative", "literal"),
                 meaning = c("kill", "seek", "seek", "kill"), 
                 amount = c(47, 2260, 588, 5639)) 

ggplot(df, aes(x=speech,y=amount, fill=meaning, group = meaning)) + 
  geom_bar(stat = "identity", position="fill") +
  # 新增文本标签层
  geom_text(aes(label = amount), 
            position = position_fill(vjust = 0.5), # 对齐比例堆叠的位置,vjust设为0.5实现居中
            size = 3.5) # 可根据需要调整字体大小

参数说明:

  • aes(label = amount) 直接指定用原始的实际数值作为标签内容,不会自动转换为比例
  • position = position_fill(vjust = 0.5) 保证文本和对应色块的位置完全匹配,vjust = 0.5控制标签在色块内部垂直居中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:39:04