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

如何为ggplot2箱线图添加样本量(n)或汇总统计标签?

为ggplot箱线图添加样本量标签的简单方法

对于新手来说,最直观不易出错的方法分为两步:先统计各分组的样本量,再用geom_text将标签添加到图上。以下是适配你代码的完整解决方案:

步骤1:提前统计各年份的样本量

在绘图前,先从过滤后的数据中计算每个年份的样本量,同时标记对应的x轴位置:

# 先过滤数据并保存为临时对象
filtered_data <- total %>% 
  filter(year %in% c(1977, 2020, 2021, 1992),
         sampletype == "groundwater",
         East == 1,
         variable %in% c("EC_uS"))

# 统计每个年份的样本量
sample_counts <- filtered_data %>%
  group_by(year) %>%
  summarize(n = n(),
            x_pos = as.character(year)) # 和x轴的字符型年份对应

步骤2:在ggplot中添加样本量标签

把统计好的样本量数据传入geom_text,指定标签位置(这里设置在箱线图上方,你可以根据数据调整y值):

bp_east_EC <- ggplot(filtered_data, aes(x = as.character(year), y = value, colour = as.factor(year))) +
  theme_ipsum() +
  ggtitle("Groundwater EC, eastern Curacao") +
  theme(plot.title = element_text(hjust = 0.5, size=14),
        legend.position = "none") +
  labs(x="", y="uS/cm") +
  geom_jitter(color="grey", size=0.4, alpha=0.9) +
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=23, size=2) + # 显示均值
  # 添加样本量标签
  geom_text(data = sample_counts, 
            aes(x = x_pos, y = max(filtered_data$value) * 1.05, # 放在数据最大值的1.05倍位置
                label = paste0("n = ", n)),
            colour = "black", size=4)

另一种更简洁的方法(无需提前统计)

如果你不想单独统计数据,可以直接用stat_summary自动计算样本量并添加标签,适合熟悉ggplot语法的新手:

bp_east_EC <- filtered_data %>%
  ggplot(aes(x = as.character(year), y = value, colour = as.factor(year))) +
  theme_ipsum() +
  ggtitle("Groundwater EC, eastern Curacao") +
  theme(plot.title = element_text(hjust = 0.5, size=14),
        legend.position = "none") +
  labs(x="", y="uS/cm") +
  geom_jitter(color="grey", size=0.4, alpha=0.9) +
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=23, size=2) +
  # 用stat_summary直接生成样本量标签
  stat_summary(fun = function(x) max(x)*1.05, # 标签y位置
               geom = "text", 
               aes(label = paste0("n = ", length(x))),
               colour = "black", size=4)

注意事项

  • 你之前尝试的mtext是base R绘图的函数,和ggplot不兼容,所以会出错;annotate需要手动逐个指定每个标签的位置,对于多个分组来说效率低且容易出错。
  • 如果想把标签放在箱线图内部(比如顶部或底部),只需要调整y参数的值,比如用min(filtered_data$value)*0.95放在下方。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:15:37