stat_compare_mean() 不适用于具有多个 y 值的 ggboxplot()

stat_compare_mean() does not work on ggboxplot() with multiple y values

我正在尝试使用 ggboxplpot 将 p 值添加到我的箱线图中,但是当我有多个 y = 值时,stat_compare_means() 似乎不起作用。

这里是来自 palmerpenguin 数据集的示例代码

library(palmerpenguins) 
library(tidyverse) 
library(ggplot2)
library(ggpubr)

#Load data
data(package = 'palmerpenguins')

#Remove NA data
df_clean <- na.omit(penguins)

#Group dataset according to species
df_new <- df_clean %>% 
  group_by(species)

#Generate multiple boxplots
df_boxplot <- ggboxplot(df_new, 
                  x = "species", 
                  y = c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"),
                  ylab = "Bill Length (mm)", 
                  xlab = "Species", 
                  color = "species", 
                  fill = "species", 
                  notch = TRUE, 
                  alpha = 0.5, 
                  ggtheme = theme_pubr()) +
                  stat_compare_means()
df_boxplot

我也试过添加比较列表,但没用

我添加了这个变量:

comp_list <- list(c("Chinstrap", "Adelie"), c("Chinstrap", "Gentoo"), c("Adelie", "Gentoo"))

然后将 stat_compare_nea() 更改为 stat_compare_nea(comparison = comp_list)

我希望有人可以提供替代方案并解释为什么这不起作用。为什么 stat_compare_mean() 不会自动将 p 值添加到在 df_boxplot

中创建的 4 个不同的箱线图中

问题是 ggboxplot return 是一个 ggplot 的列表,每个变量对应一个。因此,将 + stat_compare_means() 添加到列表将不起作用,而是 return NULL.

要将 p-values 添加到您的每个地块,必须使用例如将 + stat_compare_means() 添加到列表的每个元素lapply:

library(palmerpenguins)
library(tidyverse)
library(ggplot2)
library(ggpubr)

# Remove NA data
df_clean <- na.omit(penguins)

# Group dataset according to species
df_new <- df_clean %>%
  group_by(species)

# Generate multiple boxplots
df_boxplot <- ggboxplot(df_new,
  x = "species",
  y = c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"),
  ylab = "Bill Length (mm)",
  xlab = "Species",
  color = "species",
  fill = "species",
  notch = TRUE,
  alpha = 0.5,
  ggtheme = theme_pubr()
)

lapply(df_boxplot, function(x) x + stat_compare_means())
#> $bill_length_mm

#> 
#> $bill_depth_mm