You need to enable JavaScript to run this app. ggplot2使用position='fill'的堆叠条形图添加数值标签问题
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2使用position='fill'的堆叠条形图添加数值标签问题

ggplot堆叠百分比条形图加标签方案

两种实现方式都可行,不需要强制提前手动计算百分比,你可以根据实际需求选择:

方案1:直接用geom_bar()实现,无需提前处理数据

geom_bar()默认的统计转换(stat="count")会自动计算分组计数和组内占比,你可以通过after_stat()直接调用计算好的占比生成标签:

library(tidyverse)
library(scales) # 用于格式化百分比展示,可选

df <- data.frame(var1 = sample(c("A","B"), size = 100, replace=TRUE),
                 var2 = sample(c("x", "y"), size=100, replace=TRUE))

df %>% 
  ggplot(aes(x = var1, fill = var2)) + 
  geom_bar(position = 'fill') +
  geom_text(
    stat = "count",
    aes(label = after_stat(scales::percent(prop))),
    position = position_fill(vjust = 0.5) # 让标签在堆叠块内居中显示
  )

说明:prop是stat="count"默认计算的变量,代表每个子组(var2的类别)在对应x轴分组(var1的类别)内的占比;position_fill(vjust=0.5)保证标签和对应堆叠块位置对齐。


方案2:提前计算百分比后用geom_col()实现

如果需要对百分比做额外处理、或者需要标注更多衍生指标,更推荐先汇总数据再绘图,可控性更高:

df %>%
  # 先统计每个分组的数量,计算占比
  count(var1, var2) %>%
  group_by(var1) %>%
  mutate(pct = n / sum(n)) %>%
  ggplot(aes(x = var1, y = pct, fill = var2)) +
  geom_col(position = "fill") +
  geom_text(
    aes(label = scales::percent(pct)),
    position = position_fill(vjust = 0.5)
  )

内容的提问来源于stack exchange,提问作者D. Studer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 17:48:01