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

如何在ggplot柱状图的指定条形上添加单个百分比标签

仅为分组柱状图指定条形添加百分比标签的解决方案

问题背景

绘制分组柱状图时,需仅为每组的第二个条形(number_of_courses为Courses With Issues的类别)添加百分比标签,而非所有条形都显示标签。现有数据如下:

structure(list(source = c("College Provided", "College Provided", 
"Corporate", "Corporate", "Course Production", "Course Production"
), divided_column = c(36.8421052631579, 36.8421052631579, 50, 
50, 75.609756097561, 75.609756097561), number_of_courses = structure(c(1L, 
2L, 1L, 2L, 1L, 2L), levels = c("Total Courses", "Courses With Issues"
), class = "factor"), value = c(19L, 7L, 6L, 3L, 41L, 31L)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

解决方案

可以通过两种方式实现需求:

方法一:用条件判断控制标签显示

在geom_text的label参数中,通过ifelse函数仅为目标类别生成标签,其余情况返回空字符串:

ggplot(total_courses_issues_long,  
       aes(x = fct_infreq(source), y = value, fill = number_of_courses)) + 
  geom_bar(stat = "identity", position = "dodge", width = 0.6) + 
  geom_text(aes(label = ifelse(number_of_courses == "Courses With Issues", 
                               paste0(round(divided_column, 2), "%"), "")), 
            position = position_dodge(width = 0.9), 
            vjust = -0.5, size = 3)

方法二:筛选数据集传入geom_text

直接给geom_text传入仅包含目标类别的筛选后数据集,从源头上限制标签的生成范围:

ggplot(total_courses_issues_long,  
       aes(x = fct_infreq(source), y = value, fill = number_of_courses)) + 
  geom_bar(stat = "identity", position = "dodge", width = 0.6) + 
  geom_text(data = subset(total_courses_issues_long, number_of_courses == "Courses With Issues"),
            aes(label = paste0(round(divided_column, 2), "%")), 
            position = position_dodge(width = 0.9), 
            vjust = -0.5, size = 3)

原理说明

  • 方法一利用条件逻辑,仅在匹配目标条形时输出有效标签,空字符串不会在图中显示任何内容。
  • 方法二通过subset函数过滤数据,只让geom_text处理需要添加标签的行,效率更高且逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:13:09