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

ggplot2分组计数条形图:如何为单个条形添加数值标签?

问题:ggplot2分组条形图无法为单个并列条形添加对应数值标签

使用泰坦尼克号数据集制作分组计数条形图时,尝试为每个并列的条形(如一等舱存活/未存活)添加数值标签,但当前标签显示的是每个客舱等级的总计数,而非分组后的对应数值。

现有代码:

titanic <- read_csv("titanic.csv")

titanicgg <- ggplot(titanic)

titanicgg + geom_bar(aes(x=Pclass, fill=as.factor(Survived)), position=position_dodge2(preserve = "single")) + 
    labs(title="Survival by Passenger Class", x = "Passenger Class", y = "Count") + 
    theme_classic() + theme(plot.title = element_text(hjust = .5)) + 
    scale_fill_manual(values = c("red3", "steelblue3"), name=element_blank(), 
                      labels=c("Did Not Survive", "Survived")) + 
    theme(plot.title=element_text(size=25, face="bold"), axis.title=element_text(size=15), 
          legend.text = element_text(size = 13)) +
    geom_text(stat = 'count',aes(label = ..count.., vjust = -0.2, x=Pclass), position = position_dodge(.9))

解决方案

问题出在geom_text的aes映射中未包含分组变量Survived,导致统计的是每个Pclass的总计数,而非分组后的单独计数。修改方式如下:

  1. 在geom_text的aes里添加fill=as.factor(Survived),让ggplot按存活状态分组统计计数;
  2. 确保position_dodge的宽度与geom_bar的position_dodge2匹配,保证标签与对应条形对齐。

修改后的完整代码:

titanic <- read_csv("titanic.csv")

titanicgg <- ggplot(titanic)

titanicgg + geom_bar(aes(x=Pclass, fill=as.factor(Survived)), position=position_dodge2(preserve = "single", width = .9)) + 
    labs(title="Survival by Passenger Class", x = "Passenger Class", y = "Count") + 
    theme_classic() + theme(plot.title = element_text(hjust = .5)) + 
    scale_fill_manual(values = c("red3", "steelblue3"), name=element_blank(), 
                      labels=c("Did Not Survive", "Survived")) + 
    theme(plot.title=element_text(size=25, face="bold"), axis.title=element_text(size=15), 
          legend.text = element_text(size = 13)) +
    geom_text(stat = 'count', aes(x=Pclass, fill=as.factor(Survived), label = ..count..), 
              vjust = -0.2, position = position_dodge(.9))

关键说明

  • 给geom_bar的position_dodge2指定width=.9,和geom_text的position_dodge(.9)保持一致,确保标签精准对齐每个条形;
  • geom_text的aes必须包含fill=as.factor(Survived),这样stat='count'才会按分组计算每个条形的数量,而非总计数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:35:19