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

比例失衡时ggplot中geom_bar(position="fill")后geom_text标注位置异常问题

解决ggplot分组比例文本定位问题

问题核心是你的sum(after_stat(count))计算的是全局总数,而非按patient分组的总数,导致Sick组的标签被挤至边缘位置。无需提前预处理数据,直接在ggplot内调整统计量的分组规则和映射逻辑即可解决:

修正后的代码

# mock data    
mock.data <- data.frame(
      patient=c(rep("Healthy", 9925), rep("Sick", 75)),
      drug=c(rep(c("A", "B"), 5000)))

# 调整后的绘图代码
ggplot(mock.data, aes(y=patient, fill=drug))+
  geom_bar(position="fill")+
  geom_text(
    stat = "count",
    aes(
      label = after_stat(count),
      # 按patient分组计算组内比例,替代全局求和
      x = after_stat(count / ave(count, patient)),
      group = drug
    ),
    # 用position_fill匹配geom_bar的fill布局,vjust=0.5实现文本居中
    position = position_fill(vjust = 0.5)
  )+
  xlab("proportion")

关键调整说明

  • 替换比例计算逻辑:将x = after_stat(count)/sum(after_stat(count))改为x = after_stat(count / ave(count, patient)),ave(count, patient)会按patient分组计算每组的总数,确保比例是组内占比而非全局占比。
  • 匹配定位方式:改用position_fill(vjust=0.5)替代position_stack(0.5),让文本自动适配geom_bar(position="fill")的坐标系统,在对应比例条内居中显示。

更简洁的替代写法

利用ggplot内置的prop统计量,通过指定分组规则直接计算组内占比:

ggplot(mock.data, aes(y=patient, fill=drug))+
  geom_bar(position="fill")+
  geom_text(
    stat = "count",
    aes(
      label = after_stat(count),
      x = after_stat(prop),
      # 指定按patient分组计算比例
      group = patient
    ),
    position = position_fill(vjust = 0.5)
  )+
  xlab("proportion")

内容的提问来源于stack exchange,提问作者Pau Clavell-Revelles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:42:41