R语言 编写加显著性的分面箱线图函数及文本处理

2023-11-22  本文已影响0人  风知秋

selected_categories2 <- c("REF", "HET", "ALT")

comparisons2 <- list(c("REF", "ALT"))

create_boxplot <- function(x, selected_variable) {

  x2 <- x[x[[selected_variable]] %in% selected_categories2, ]

  x2[[selected_variable]] <- factor(x2[[selected_variable]], level=c("REF", "HET", "ALT"))

  ggplot(x2, aes(x = !!sym(selected_variable), y = FH)) +

    geom_boxplot() +

    geom_point(position = position_jitter(width = 0.2), alpha = 0.5) +

    geom_signif(comparisons = comparisons2, test = wilcox.test, map_signif_level = T, color = "black", textsize = 4, step_increase = 0.5, y_position = 250) +

facet_grid(. ~ Species) +

    xlab(paste("\n", selected_variable)) 

}

selected_variable <- "X36357203"

create_boxplot(x, selected_variable)


之前写的有点乱,现在将函数编写过程理一下:

selected_categories <- c("REF", "HET", "ALT")

首先,对于每一列,仅挑选特定的行,每一列可能有多种数据,包括 NA 之类的缺失值,现在仅对 selected_categories  中指定的行进行分析。

x2 <- x[x[[selected_variable]] %in% selected_categories, ]

得到的 x2 是一个新的数据框,仅包括 selected_variable 这一列中内容为 "REF", "HET", "ALT" 的行。

geom_point(position = position_jitter(width = 0.2), alpha = 0.5) 

在箱线图的基础画上点的分布,方便识别每个 box 中的样本数目和分布。

xlab(paste("\n", selected_variable)) 

每个图的横坐标题目使用了 paste 连接两个字符串,这里连接的是换行符,增加标题距横轴的距离。

 geom_signif(comparisons = comparisons2, test = wilcox.test, map_signif_level = T, color = "black", textsize = 4, step_increase = 0.5, y_position = 250)

增加了显著性分析,comparisons 可以指定都是哪些之间进行比较,还有一些其它可修改的参数。

上一篇 下一篇

猜你喜欢

热点阅读