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

ggplot2分组箱线图中stat_pvalue_manual()报错:找不到Temperature对象

解决stat_pvalue_manual()绘制分组箱线图p值报错问题

报错信息:

! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error:
! object 'Temperature' not found

问题根源

你的ggplot全局美学映射(aes(x = Species, y = Cell.size, fill = Temperature))包含了fill = Temperature,但stat_pvalue_manual调用的数据集contrasts.means.species.temp里没有Temperature列,且未关闭全局美学映射继承,导致该图层尝试寻找不存在的变量而报错。同时,因为是在每个物种内部对比两个温度组,还需要让标注对齐分组的位置,和前面箱线图的dodge宽度匹配。

修复后的完整代码

# Load required libraries
library(ggplot2)
library(dplyr)
library(ggpubr)

# Create dummy raw data
set.seed(123)
temp.subset.species <- expand.grid(
  Species = factor(c("Species 1", "Species 2", "Species 3", "Species 4", "Species 5")),
  Temperature = factor(c(28, 30))
) %>%
  group_by(Species, Temperature) %>%
  do(data.frame(Cell.size = rnorm(10, mean = sample(120:160, 1), sd = 5)))

# Create dummy estimated marginal means data
means.temp.species <- temp.subset.species %>%
  group_by(Species, Temperature) %>%
  summarise(
    emmean = mean(Cell.size),
    lower.CL = emmean - 5,
    upper.CL = emmean + 5,
    .groups = "drop"
  )

# Create dummy p-value annotation data
contrasts.means.species.temp <- data.frame(
  Species = factor(c("Species 1", "Species 2", "Species 3", "Species 4", "Species 5")),
  group1 = factor(rep(28, 5)),
  group2 = factor(rep(30, 5)),
  p.value.signif = c("ns", "*", "ns", "ns", "*"),
  y.position = rep(200, 5)
)

# Plot
ggplot(temp.subset.species, aes(x = Species, y = Cell.size, fill = Temperature)) +
  geom_boxplot(
    aes(color = Temperature),
    position = position_dodge(width = 0.75),
    width = 0.5
  ) +
  geom_point(
    data = means.temp.species,
    aes(x = Species, y = emmean, group = Temperature),
    color = "black",
    shape = 21,
    size = 3,
    position = position_dodge(width = 0.75)
  ) +
  geom_errorbar(
    data = means.temp.species,
    aes(x = Species, ymin = lower.CL, ymax = upper.CL, group = Temperature),
    color = "black",
    width = 0.2,
    position = position_dodge(width = 0.75),
    inherit.aes = FALSE
  ) +
  stat_pvalue_manual(
    data = contrasts.means.species.temp,
    label = "p.value.signif",
    inherit.aes = FALSE,  # 关键:关闭全局美学映射继承
    aes(x = Species),     # 指定x轴对应物种分组
    position = position_dodge(width = 0.75)  # 匹配前面图层的dodge宽度,保证标注对齐
  )

关键修改说明

  • inherit.aes = FALSE:阻止该图层继承全局的fill = Temperature映射,避免查找不存在的变量。
  • aes(x = Species):明确指定p值标注对应每个物种的位置。
  • position = position_dodge(width = 0.75):和箱线图、均值点的dodge宽度保持一致,确保p值线与标注对齐到每个物种的两个温度组中间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:05:20