user3324491
user3324491

Reputation: 559

can't open pdf plot r

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()
}

Upvotes: 1

Views: 2640

Answers (2)

Bioinfotec
Bioinfotec

Reputation: 93

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.

Upvotes: 0

IRTFM
IRTFM

Reputation: 263481

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.

Upvotes: 2

Related Questions