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

如何在百分比条形图顶部添加总数?代码报错求助

问题解决与代码修正

报错原因分析

  1. 包名错误:调用了不存在的ggplot包,正确包名为ggplot2
  2. 全局美学映射冗余:主图aes里写了无效的label = ,需删除
  3. 美学映射继承冲突:geom_text继承了全局的fill映射,但totals数据集没有severity_fatigue变量,导致找不到对象
  4. 轴类型不匹配:主图x轴是因子化的event_number,但totals中是原始类型,会导致文本位置错位
  5. 坐标值错误:position="fill"的y轴范围是0-1(比例值),geom_text里设y=100超出范围,无法正确显示

修正后的完整代码

library(scales)
library(ggplot2)  # 修正包名
library(dplyr)

# 计算分组总数,用n()更简洁,同时提前因子化event_number和主图匹配
totals <- pasc_both %>%
    group_by(event_number) %>%
    summarize(total = n()) %>%  # n()等价于length(severity_fatigue)
    mutate(event_number = factor(event_number,
                                 levels = c("0", "1", "2","3", "4", "5", 
                                            "6", "7", 
                                            "8", "9", "10", "12", "14")))

sfatigue_plot <- ggplot(pasc_both, 
       aes(x = factor(event_number,
                      levels = c("0", "1", "2","3", "4", "5", 
                                "6", "7", 
                                "8", "9", "10", "12", "14")),
           fill = factor(severity_fatigue, 
                         levels = c("None", "Mild", "Moderate", "Severe")))) +  # 删除无效的label=
  geom_bar(position = "fill") +
  scale_y_continuous(breaks = seq(0, 1, .2), 
                     labels = percent) +  # 修正label为labels
  scale_fill_brewer(palette = "Set2") +
  labs(y = "Percent", 
       fill = "Symptom Severity",
       x = "Week",
       title = "Fatigue") +
  theme_minimal() +
  geom_text(data = totals,
            aes(y = 1,  # 改为比例范围的最大值1
                x = event_number,
                label = total),
            size = 7,
            position = position_fill(vjust = 1.02),
            inherit.aes = FALSE)  # 禁止继承全局美学,避免fill映射冲突

关键修改说明

  • 修正ggplot为ggplot2,确保包正确加载
  • 删除全局aes中无效的label = 语句
  • 在geom_text中添加inherit.aes = FALSE,避免继承全局的fill映射,解决severity_fatigue找不到的问题
  • 提前将totals中的event_number因子化,和主图x轴类型保持一致,保证文本位置准确
  • 将geom_text的y值改为1,匹配position="fill"的y轴比例范围,同时通过vjust=1.02让文本显示在条形顶部外侧
  • 把scale_y_continuous的label参数修正为labels(复数形式,这是ggplot2的正确参数名)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:05:33