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

ggplot2中geom_bar添加计数文本报错及多场景实现方法咨询

解决方法

1. 普通柱状图添加计数文本

你的错误是因为geom_text未指定必要的x、y映射,且错误把label设为字符串"count"。正确做法是利用ggplot的统计变量after_stat(count)获取柱形计数,同时对齐x轴映射:

ggplot(data=auftraege_gefiltert_kopf) +
  geom_bar(mapping = aes(x=AuftragsTyp)) +
  # 计数文本放在柱形上方,可调整vjust控制位置
  geom_text(aes(x=AuftragsTyp, label=after_stat(count)), 
            stat="count",
            vjust=-0.5) +
  dark_theme_grey()

若要把文本放在柱形内部,调整vjust=0.5即可:

geom_text(aes(x=AuftragsTyp, label=after_stat(count)), 
          stat="count",
          vjust=0.5)

2. 带fill参数的横向柱状图添加计数文本

横向柱状图中y轴是分类变量(Mitarbeiter),x轴为计数,fill参数按Fakturiert分组堆叠。需确保geom_text的位置与柱形的堆叠/分组逻辑一致:

堆叠式横向柱状图(默认geom_bar行为)

ggplot(data=auftraege_kopf_positionen) +
  geom_bar(mapping = aes(y=Mitarbeiter, fill = Fakturiert)) +
  # 文本居中在堆叠块内
  geom_text(aes(y=Mitarbeiter, label=after_stat(count)),
            stat="count",
            position=position_stack(vjust=0.5)) +
  dark_theme_grey()

分组式横向柱状图(并列显示Fakturiert水平)

若要改为分组显示,需给geom_bar和geom_text统一设置position="dodge":

ggplot(data=auftraege_kopf_positionen) +
  geom_bar(mapping = aes(y=Mitarbeiter, fill = Fakturiert),
           position=position_dodge(width=0.9)) +
  geom_text(aes(y=Mitarbeiter, label=after_stat(count)),
            stat="count",
            position=position_dodge(width=0.9),
            hjust=-0.1) + # 文本放在分组柱形右侧
  dark_theme_grey()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:01:01