使用R语言批量作箱线图

由于需要输出比较多的图,使用批量思维来处理

我的exprSet文件是这样的

分别做每个基因的箱线图,重新生成每个基因的文件test2,如下:


全部代码如下:

colnames(exprSet)[1] <-"Group"

for (i in 2:length(colnames(exprSet))) {

  test2 <- exprSet[,c(1,i)]

  test2$Group<- factor(test2$Group)

  png(filename = paste0(i, "_", ".jpg"),width = 2400,height = 4000,res = 300)

  print(ggplot(data = test2,aes_string(x = "Group",y=colnames(test2)[2])) +

          geom_boxplot(aes(x = Group, y = test2[,2], color = Group)) +

          geom_jitter(aes(x = Group, y =test2[,2], color = Group),

                      position = position_jitterdodge())+

          theme_bw()+

          ggtitle(colnames(test2)[2]) +

          theme(plot.title = element_text(hjust = 0.5)))

  dev.off()


}

将生成的图合并在一起,可以用pachwork包,这个包适用于ggplot函数

p = list()

for (i in 2:length(colnames(exprSet))) {

  test2 <- exprSet[,c(1,i)]

  test2$Group<- factor(test2$Group)

  p[[i-1]]=ggplot(data = test2,aes_string(x = "Group",y=colnames(test2)[2])) +

          geom_boxplot(aes(x = Group, y = test2[,2], color = Group)) +

          geom_jitter(aes(x = Group, y =test2[,2], color = Group),

                      position = position_jitterdodge())+

          theme_bw()+

          ggtitle(colnames(test2)[2]) +

          theme(plot.title = element_text(hjust = 0.5))

}

install.packages("patchwork",ask=F,update=F)

library(patchwork)

wrap_plots(p,nrow = 1,guides = "collect")

生成的图如下:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容