1

For some reason, in this loop the PDFs that it produces end up corrupt. However, when I plot each individually it is saved and I can open them. Please advise, going mad!

for (l in 1:length(which_genes)) {
        gene_name <- which_genes[[l]]
        cases_values <- cases[cases$HGNC == genes[gene_name],]
        controls_values <- controls[controls$HGNC == genes[gene_name],]
        t <- t.test(cases_values[c(2:ncol(cases_values))], controls_values[c(2:ncol(controls_values))])
        case <- cbind(t(cases_values[c(2:ncol(cases_values))]), "cases")
        cont <- cbind(t(controls_values[c(2:ncol(controls_values))]), "controls")
        dat <- as.data.frame(rbind(case, cont))
        names(dat) <- c("expression", "type")
        dat$expression <- as.numeric(dat$expression)
        #plot significant genes
        pdf(file = paste(genes[gene_name], "_different.pdf", sep=""))
        ggplot(dat, aes(type, expression, fill=type)) + 
        geom_boxplot() +
        ggtitle(paste(genes[gene_name], "pvalue", t$p.value)) + 
        xlab("cases vs controls")
        dev.off()
}
user3324491
  • 539
  • 1
  • 4
  • 14
  • Can you add a sample of your data? http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Travis Mar 09 '17 at 18:54
  • Try using Sys.sleep to give ggplot2/grid more time to finish the plot. – Roland Mar 09 '17 at 19:00
  • @Roland I tried Sys.sleep(5) before and after the pdf, now I can see the size of the plot being saved from 163bytes to 4KB - still corrupt. When I plot without the loop the PDF saved that opens is 5KB. Do you have any other suggestions? – user3324491 Mar 09 '17 at 19:16
  • Have you put it before dev.off? Make sure that you have closed all open devices before testing the code. – Roland Mar 09 '17 at 19:18
  • @Roland, yes! before dev.off, I tried 5, 10, and now 20... It's the tinniest boxplot, how much time do you think it needs? – user3324491 Mar 09 '17 at 19:20

2 Answers2

2

Yet another instance of the failure-to-print error (as described in the R-FAQ). Use this instead inside the loop:

pdf(file = paste(genes[gene_name], "_different.pdf", sep=""))
    print( ggplot(dat, aes(type, expression, fill=type)) + 
    geom_boxplot() +
    ggtitle(paste(genes[gene_name], "pvalue", t$p.value)) + 
    xlab("cases vs controls")
          )
dev.off()

If the goal was to have a multi-page output then you should have opened the PDF-device outside the loop, print-ed within the loop, and then closed the device outside.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

You should print the plot before dev.off(). For during the drawing process of ggplot2, the graphics are not displayed on the drawing device immediately, but are drawn when they need to be displayed or saved.

Fei
  • 51
  • 4