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

如何在同一张多箱线图中为各标记的不同地点添加统计显著性标记?

解决方案

要实现每种标记(category)内部不同地点(place)的显著性比较,且不跨标记比较,可以借助ggsignif包的geom_signif函数,它能针对分组变量单独设置组内比较,同时通过位置对齐匹配箱线图的排列。

修改后的完整代码

library(ggplot2)
library(dplyr)
library(tidyr)
library(ggpubr)
library(ggsignif)  # 新增包,用于分组添加显著性标记

data <- data.frame(
  fat = rep(c("Lake A", "Lake B", "Lake C"), each = 50),
  zon = c(rnorm(50, mean = 5, sd = 1), rnorm(50, mean = 5.5, sd = 1), rnorm(50, mean = 4.5, sd = 1)),
  cal = c(rnorm(50, mean = 6, sd = 1.5), rnorm(50, mean = 6.5, sd = 1.5), rnorm(50, mean = 5.5, sd = 1.5)),
  si = c(rnorm(50, mean = 7, sd = 1), rnorm(50, mean = 7.5, sd = 1), rnorm(50, mean = 6.5, sd = 1)), 
  other1 = rnorm(150),other2 = rnorm(150))

data_selected <- data %>% select(place = fat, zon, cal, si)
data_long <- pivot_longer(data_selected, cols = c("zon", "cal", "si"), names_to = "category", values_to = "value")

ggplot(data_long, aes(x = place, y = value, fill = category)) +
  geom_boxplot(position = position_dodge(width = 0.8)) +  # 指定箱线图间距,用于后续对齐
  labs(title = NULL,
       x = "Location",
       y = "Marker level (Log-values)",
       fill = "Marker") +
  theme_bw() +
  theme(legend.position = "top") +
  # 添加分组显著性标记
  geom_signif(
    aes(group = category),  # 指定按标记分组,仅在组内比较地点
    comparisons = list(c("Lake A", "Lake B"), c("Lake A", "Lake C"), c("Lake B", "Lake C")),  # 组内两两比较组合
    test = "t.test",  # 沿用原代码的检验方法
    map_signif_level = TRUE,  # 显示显著性符号(*、**等)而非原始p值
    size = 1,  # 显著性横线的粗细
    textsize = 5,  # 符号大小
    position = position_dodge(width = 0.8)  # 和箱线图间距对齐,确保标记对应正确分组
  )

关键说明

  • position_dodge(width = 0.8):保证箱线图和显著性标记的位置完全对齐,避免标记错位。
  • aes(group = category):限制显著性比较仅在同一个标记组内进行,不会跨标记绘制对比线条。
  • comparisons参数:定义每个标记组内需要比较的地点组合,这里包含了三个地点的所有两两对比。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:12:06