Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save ggplot within a function

Tags:

r

ggplot2

I'm trying to save a ggplot within a function using graphics devices. But I found the code produces empty graphs. Below is a very very simple example.

library(ggplot2)
ff <- function(){
  jpeg("a.jpg")
  qplot(1:20, 1:20)
  dev.off()
}
ff()

If I only run the content of the function, everything is fine. I know that using ggsave() will do the thing that I want, but I am just wondering why jpeg() plus dev.off() doesn't work. I tried this with different versions of R, and the problem persists.

like image 340
Wei Wang Avatar asked Aug 12 '11 01:08

Wei Wang


2 Answers

You should use ggsave instead of the jpeg(); print(p); dev.off() sequence. ggsave is a wrapper that does exactly what you intend to do with your function, except that it offers more options and versatility. You can specify the type of output explicitly, e.g. jpg or pdf, or it will guess from your filename extension.

So your code might become something like:

p <- qplot(1:20, 1:20)
ggsave(filename="a.jpg", plot=p)

See ?ggsave for more details


The reason why the original behaviour in your code doesn't worked is indeed a frequently asked question (on stackoverlflow as well as the R FAQs on CRAN). You need to insert a print statement to print the plot. In the interactive console, the print is silently execututed in the background.

like image 170
Andrie Avatar answered Nov 10 '22 08:11

Andrie


These plots have to be printed:

ff <- function(){
  jpeg("a.jpg")
  p <- qplot(1:20, 1:20)
  print(p)
  dev.off()
}
ff()

This is a very common mistake.

like image 21
joran Avatar answered Nov 10 '22 10:11

joran