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

如何在ggplot柱状图的计数旁添加括号形式的百分比

解决ggplot柱状图顶部同时显示计数与百分比的问题

已在ggplot柱状图的顶部添加了计数(count),但无法实现在计数旁的括号中添加百分比的效果。尝试操作后,柱状图顶部显示的是prop*100而非正确的百分比。以下是仅生成计数的代码:

df %>% 
  ggplot(aes(x = day_of_week, fill = day_of_week)) +
    geom_bar(position = "dodge") +
    geom_text(aes(label = ..count..), stat = "count", vjust = -1.0, colour = "black") +
    ylim(0, 2600) +
    theme_classic() +
    theme(legend.position="none",
           axis.text.x = element_text(angle=45, hjust=1)
          ) +
  scale_fill_brewer(palette = 1, direction = - 1) +
    xlab("day_of_week") +
    ylab("Count (n)")

核心修改geom_text的参数即可实现需求,关键是正确计算百分比并拼接文本,同时设置group确保百分比基于整体数据计算:

修改后的完整代码:

df %>% 
  ggplot(aes(x = day_of_week, fill = day_of_week)) +
    geom_bar(position = "dodge") +
    # 关键修改:拼接计数与百分比,设置group=1确保百分比计算正确
    geom_text(aes(label = paste0(..count.., " (", round(..prop..*100, 1), "%)"), 
                  group = 1), 
              stat = "count", vjust = -1.0, colour = "black") +
    ylim(0, 2600) +
    theme_classic() +
    theme(legend.position="none",
           axis.text.x = element_text(angle=45, hjust=1)
          ) +
  scale_fill_brewer(palette = 1, direction = - 1) +
    xlab("day_of_week") +
    ylab("Count (n)")

关键修改点说明:

  • 在geom_text的aes中,用paste0()将计数(..count..)和百分比(round(..prop..*100, 1))拼接成计数 (百分比%)的格式,round()用于控制百分比的小数位数(这里保留1位)
  • 必须添加group = 1:因为stat="count"默认会按x的每个类别分组计算占比,导致每个柱子的百分比都是100%,group=1会让百分比基于所有数据的总数计算
  • 如果需要按其他维度计算百分比,可将group设置为对应变量,比如按某分类列分组计算组内占比

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:36:14