This is a test version of Biostars. For the public version, visit https://www.biostars.org.
question about R language 'for' loop

When I type in the following code, the resulting picture is blank

samples <- c("m5C","m6A","m7G")
group <- c("Control","Treatment")
for(sa in samples){
for(gr in group){
  genelist = bitr(geneID = metG.expr[[sa]][[gr]]$Symbol,fromType = "SYMBOL",toType = "ENTREZID",OrgDb = org.Dr.eg.db)
  kegg <- enrichKEGG(gene = genelist$ENTREZID,
                     keyType = "kegg",organism = "dre",
                     pvalueCutoff = 0.05,pAdjustMethod = "BH")
  png(paste("./exprProfile/enrich/",sa,".",gr,".kegg",".png",sep=""),width = 1500,height = 1000,res = 200)
  ggplot(kegg@result[c(1:10),],mapping = aes(x = Description,y = -log10(pvalue),fill = pvalue))+
    geom_bar(stat = "identity",show.legend = T)+ 
    coord_flip()+scale_fill_gradient2(high="blue",mid = "red")
  dev.off()
}}

but when i assign values to two variables 'sa' and 'gr'

sa<-"m5C"
gr<-"Control"

then run

genelist = bitr(geneID = metG.expr[[sa]][[gr]]$Symbol,fromType = "SYMBOL",toType = "ENTREZID",OrgDb = org.Dr.eg.db)
  kegg <- enrichKEGG(gene = genelist$ENTREZID,
                     keyType = "kegg",organism = "dre",
                     pvalueCutoff = 0.05,pAdjustMethod = "BH")
  png(paste("./exprProfile/enrich/",sa,".",gr,".kegg",".png",sep=""),width = 1500,height = 1000,res = 200)
  ggplot(kegg@result[c(1:10),],mapping = aes(x = Description,y = -log10(pvalue),fill = pvalue))+
    geom_bar(stat = "identity",show.legend = T)+ 
    coord_flip()+scale_fill_gradient2(high="blue",mid = "red")
  dev.off()

the picture is successfully produced,so i wonder what cause this situation and how i can fix that,thanks

rna-seq sequencing next-gen r gene

2 answers

Within the for loop, save the plot to a variable, and then pass that variable to the print function while the graphics device is open. R usually won't plot in a for loop unless you do so.

Alternatively you can use the ggsave function instead which will work without any problems in loops.

Use ggsave function to save ggplot picture.

Log in to answer this question.