03 R包ggpubr学习-ggboxplot

742 阅读1分钟

ggboxplot

用于绘制箱线图,相比ggplot2使绘制箱线图更加的简便

函数参数

image.png image.png image.png

width 调整箱线图的宽度

library(ggpubr)
library(patchwork)

data("ToothGrowth")
df <- ToothGrowth
head(df)
#    len supp dose group
# 1  4.2   VC  0.5  grp1
# 2 11.5   VC  0.5  grp2
# 3  7.3   VC  0.5  grp1
# 4  5.8   VC  0.5  grp2
# 5  6.4   VC  0.5  grp1
# 6 10.0   VC  0.5  grp2

plist <- lapply(c(0.2,0.4,0.8),FUN = function(x){
  ggboxplot(df, x = "dose", y = "len", width = x) + 
  ggplot2::labs(title = paste0("width = ", x))  
  })
patchwork::wrap_plots(plist, ncol = 3)

image.png

select 选择需要展示的Items

p1 <- ggboxplot(df, "dose", "len",select = c("0.5", "2"))
p2 <- ggboxplot(df, "dose", "len",select = c("0.5"))
p1|p2

image.png

通过order展示绘图的顺序

ggboxplot(df, "dose", "len",order = c("2", "1", "0.5"))

image.png

分面facet.by

ggpubr::ggboxplot(df,x = "group",
                  y = "values",
                  facet.by = "type", 
                  color = "group",
                  fill = "group", 
                  outlier.shape = NA,
                  bxp.errorbar = TRUE,
                  bxp.errorbar.width = 0.1,
                  panel.labs = list(type = c("test1",'test2','test3','test4')),
                  short.panel.labs = FALSE,
                  linetype = "solid",
                  select = c('test1','test2'),
                  width = 0.4,
                  add = "jitter",
                  add.params = list(size = 3, color = 'red'),
                  label.rectangle = FALSE
  
                  ) + 
  scale_color_manual(values = my_cols) + 
  scale_fill_manual(values = my_cols)

image.png

在箱线图中添加显著性标记

library(ggpubr)
library(patchwork)
library(rstatix)

stat.test <- df %>%
  group_by(supp, group) %>%
  t_test(len ~ dose) 

stat.test <- stat.test %>%
  add_xy_position(x = "supp", dodge = 0.8)

bp <- ggboxplot(
  df, x = "supp", y = "len", color = "dose",
  facet.by = "group",
  fill = "dose",
  scale = "free"
  ) + 
  stat_pvalue_manual(
    stat.test, label = "p.adj.signif", tip.length = 0.01,
    hide.ns = TRUE
  )+
  theme_classic() + 
  theme(strip.background = element_blank(),
        strip.text = element_text(size = 15, face = 'bold', color = 'red'),
        plot.title = element_text(hjust = 0.5))
bp

image.png

stat.test <- stat.test %>%
  add_xy_position(x = "supp", dodge = 0.8)

bp <- ggboxplot(
  df %>% dplyr::filter(supp == "OJ"), x = "supp", y = "len", color = "dose",
  facet.by = "group",
  scale = "free",
  width = 0.7
  ) + 
  stat_pvalue_manual(
    stat.test, label = "p.adj.signif", tip.length = 0.01,
    hide.ns = TRUE
  )+
  theme_classic() + 
  theme(strip.background = element_blank(),
        strip.text = element_text(size = 15, face = 'bold', color = 'red'),
        plot.title = element_text(hjust = 0.5))
bp

image.png