繁体   English   中英

在 lapply 中为每个文件创建多个图

[英]creating multiple plots for each file within lapply

我有几个文件,我正在通过 lapply 循环。 在 lapply 中,我想为每个文件制作 1 个 MAPLOT 和 1 个 Volcano plot。这是我的代码:

library(ggplot2)
library(dplyr)

files <- list.files(path = baseDir,pattern = "*.txt",full.names = T,recursive = F)

fun <- function(x){
  a <- basename(x)
  a <- gsub(".txt","",a)
  
  df <- read.table(x,header = TRUE,sep = "\t")
  df <- df[,c(1,(ncol(df)-5):(ncol(df)))]
  df <- mutate(df,threshold = ifelse(padj < 0.05,"sig","non-sig"))
  df$sigtype <- paste(df$threshold,df$type,sep="-")
  
  ## Make MAPLOT
  ggplot(df, aes(x = baseMean, y = log2FoldChange)) +
    scale_x_continuous(trans = "log10")+
    geom_point(aes(col = threshold), size = 1, shape = 20)+
    scale_color_manual(values = c("non-sig" = "gray70","sig" = "red")) +
    ylim(-5, 10)+geom_hline(yintercept = 0, linetype = "dashed",color = "black") +
    xlab("mean of normalized counts")+ theme_classic()
  
  ## Make Volcano plot
  ggplot(df, aes(x = log2FoldChange, y = -log10(padj))) +
    scale_x_continuous()+ geom_point()+ xlab("fold change")+ theme_classic()
}

lapply(files,fun)

在 Rstudio 下运行它,我预计它会为字符向量files中存在的每个输入文件(有 8 个输入文本文件)生成 1 个 MAPLOT 和 1 个 Volcano plot。 但相反,它只绘制了 8 座火山 plot。

我在这里错过了什么?

我还想要 output 1 个 pdf(volcano.pdf) 中的所有火山图,每页 1 个和另一个 pdf(maplot.pdf) 中的所有 MAPLOT,每页 1 个。 我怎样才能做到这一点?

这是一个主要是dev.set的教学示例,我在一个新的 R 进程中运行,没有任何打开的图形设备:

## Report active device
dev.cur()
## null device 
##           1

## Open device 2 and make it the active device
pdf("bar.pdf")
## Open device 3 and make it the active device
pdf("foo.pdf")

## List all open devices
dev.list()
## pdf pdf 
##   2   3

f <- function() {
    ## Plot in device 3
    plot(1:10, 1:10, main = "foo")
    ## Cycle to device 2
    dev.set()
    ## Plot in device 2
    plot(rnorm(10L), rnorm(10L), main = "bar")
    ## Cycle to device 3
    dev.set()
    invisible(NULL)
}

## Call 'f' four times
replicate(4L, f()) 

## Close device 3 and report active device
dev.off()
## pdf 
##   2

## Close device 2 and report active device
dev.off()
## null device 
##           1 

## Clean up
unlink(c("foo.pdf", "bar.pdf"))

@Limey 的建议是一次在一台设备上工作,以避免dev.set所需的簿记:

pdf("foo.pdf")
f1 <- function() {
    plot(1:10, 1:10, main = "foo")
    invisible(NULL)
}
replicate(4L, f1())
dev.off()

pdf("bar.pdf")
f2 <- function() {
    plot(rnorm(10L), rnorm(10L), main = "bar")
    invisible(NULL)
}
replicate(4L, f2())
dev.off()

unlink(c("foo.pdf", "bar.pdf"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM