Use for loop in ggplot2 to generate a list

2019-06-12 06:33发布

问题:

I would like to use for loop to generate a list of ggplots.

sig_snp<-c("rs644045_A","rs12997044_C","rs17739727_A")

p_re<-list() 

for ( i in sig_snp){
 test %>% dplyr::select(i,type,micro1) %>%
 ggplot(aes(factor(type),log(micor1) )) + 
 geom_boxplot(aes(fill = factor(i)))+
 xlab('')+ylab('log abundance')->p_re[[i]]
}

The erro shows below:

Error: All select() inputs must resolve to integer column positions. The following do not: * i

I have tested each i in the for loop in this way:

   test %>% dplyr::select(rs644045_A,type,micro1) %>%
   ggplot(aes(factor(type),log(micor1) )) + 
   geom_boxplot(aes(fill = factor(rs644045_A)))+
   xlab('')+ylab('log abundance')

It worked singly, but why not work in the loop?

回答1:

If you need to keep ggplot output per SNP in a list, it is maybe better to use lapply which will output list, e.g.:

library(ggplot2)

#dummy data
test <- mtcars

#significant SNPs
sig_snp <- c("mpg", "cyl", "disp")

#create list of ggplots per SNP
p_re <-
  lapply(sig_snp, function(i){

    ggplot(test, aes_string("qsec", i)) +
      geom_point()

    })

#assign names
names(p_re) <- sig_snp

#plot
p_re$mpg


回答2:

The tricky part is select_ and get():

The get() answers were from here : Remove quotes from a character vector in R

However, in my case,it did not work in the loop.I think it is probably due to double loops in my code (I am not sure).

Anyway, there is an alternative way to make it:

 test[,c(sig_snp,"type","micro1")]%>%
    melt(id=c("type","micro1"))%>% # head()
    ggplot(aes(factor(type),log(micro1) )) + 
    geom_boxplot(aes(fill = factor(value)))+
    xlab('')+ylab('log abundance')+facet_grid(.~variable)

I got the idea from here Looping over variables in ggplot



标签: r ggplot2 dplyr