数据准备

library(ggpubr)
library(rstatix)
# Transform `dose` into factor variable
df <- ToothGrowth
df$dose <- as.factor(df$dose)
# Add a random grouping variable
df$group <- factor(rep(c("grp1", "grp2"), 30))
head(df, 3)

统计检验

stat.test <- df %>%
  group_by(dose) %>%
  t_test(len ~ supp) %>%
  adjust_pvalue(method = "bonferroni") %>%
  add_significance()
stat.test 

绘制箱线图

# Create a box plot
bxp <- ggboxplot(
  df, x = "supp", y = "len", fill = "#00AFBB", 
  facet.by = "dose"
  )

# Make facet and add p-values
stat.test <- stat.test %>% add_xy_position(x = "supp")
bxp + stat_pvalue_manual(stat.test)

图片alt

图片alt

参考

https://rpkgs.datanovia.com/ggpubr/
https://github.com/kassambara/ggpubr
https://www.datanovia.com/en/blog/how-to-add-p-values-to-ggplot-facets/