1

This code runs fine in interactive mode and creates the plots specified. However, the plots produced when run as a script are blank. Is there a way to code this that would work both as a script and interactively? I'm using RStudio version 0.98.1091, running on 32-bit Windows 7. This works fine as a script on Linux.

library(ggplot2)

genes <- data.frame(Genes=c("A","B","C","D","E"),
                    Expression=c(1,7.6,100,2,67)
                    )

png("genes_with_legend.png")
qplot(Genes,Expression,data=genes,stat="identity",geom="bar",fill=factor(Genes))
dev.off()

png("genes_without_legend.png")
ggplot(genes,aes(Genes,Expression)) + geom_bar(stat="identity",fill=seq_along(factor(genes$Genes)),legend.position="none")
dev.off()
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99

1 Answers1

3

Save the plot to a variable, then print it:

library(ggplot2)

genes <- data.frame(Genes=c("A","B","C","D","E"),
                    Expression=c(1,7.6,100,2,67)
                    )

png("genes_with_legend.png")
plt = qplot(Genes,Expression,data=genes,stat="identity",geom="bar",fill=factor(Genes))
print(plt)
dev.off()

png("genes_without_legend.png")
plt = ggplot(genes,aes(Genes,Expression)) + geom_bar(stat="identity",fill=seq_along(factor(genes$Genes)),legend.position="none")
print(plt)
dev.off()

Values "autoprint" in interactive mode. For example, right after you type genes in interactive mode, the dataframe is printed to the screen. However, you don't expect it to be printed to a file without a print statement. Similarly, lattice/trellis/grid graphics (including ggplots) also need to be printed when not in interactive mode. Explicitly printing the plot will work for both interactive and "script" modes.

This is such a common error that it is listed in R-FAQ 7.22.

Community
  • 1
  • 1
  • This is [R-FAQ 7.22](http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f). It's not true for base plots (which aren't objects and thus aren't `print`ed,) but it is true for lattice/trellis/grid graphics (including ggplots). – Gregor Thomas Apr 09 '15 at 17:29