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

如何解决使用ggplot与ggsignif的geom_signif函数时的x轴分组报错问题

报错原因

geom_signif默认需要读取全局x轴的分组美学映射,你当前的代码未在ggplot()的全局参数中定义x映射,而是为各个图层单独手动指定x坐标,因此geom_signif无法自动识别分组逻辑,触发报错。

修复方案

最简单的修复方式是在geom_signif参数中添加manual = TRUE,开启手动指定标记位置的模式,无需修改其他原有代码。

修复后的完整可运行代码如下:

library(ggplot2)
library(ggsignif)
library(ggh4x) # 用于axis_minor坐标轴设置

d <- data.frame(y = rnorm(20, 9, 2),
                group = as.factor(rep(c('Post-FAP', 'Post-DEP'), each = 10)),
                id = rep(1:10, 2))

ggplot(d, aes(y = y)) +
  geom_boxplot(aes(x = rep(c(-2.5, 2.5), each = 10), group = group), fill = '#47E3FF') +
  geom_point(aes(x = rep(c(-1, 1), each = 10)), shape = 21, size = 1.5, col = "black", fill = "grey") +
  geom_line(aes(x = rep(c(-1, 1), each = 10), group = id)) +
  geom_signif(annotation = "p=0.05", y_position = 13, xmin = -2.5, xmax = 2.5, tip_length = .02, manual = TRUE) +
  scale_x_continuous(breaks = c(-2.5, 2.5), labels = c("Post-FAP", "Post-DEP")) +
  scale_y_continuous(minor_breaks = seq(5, 14, by =1),
                     breaks = seq(6, 14, by = 2), limits = c(5, 14),
                     guide = "axis_minor") + 
  theme_bw() +
  theme(legend.position = "none", panel.grid = element_blank())
可选优化写法

如果你希望代码更符合ggplot的语法规范,也可以直接将group映射到x轴,再通过position_nudge调整各图层的偏移位置,后续添加更多显著性标记时会更方便:

ggplot(d, aes(x = group, y = y)) +
  geom_boxplot(position = position_nudge(x = c(-1.5,1.5)), fill = '#47E3FF', width = 1) +
  geom_point(position = position_nudge(x = c(-1,1)), shape = 21, size = 1.5, col = "black", fill = "grey") +
  geom_line(aes(group = id), position = position_nudge(x = c(-1,1))) +
  geom_signif(annotation = "p=0.05", y_position = 13, xmin = 1, xmax = 2, tip_length = .02) +
  scale_x_discrete(labels = c("Post-FAP", "Post-DEP")) +
  scale_y_continuous(minor_breaks = seq(5, 14, by =1),
                     breaks = seq(6, 14, by = 2), limits = c(5, 14),
                     guide = "axis_minor") + 
  theme_bw() +
  theme(legend.position = "none", panel.grid = element_blank(),
        axis.title.x = element_blank())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:06:02