Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem saving pdf file in R with ggplot2

Tags:

macos

r

ggplot2

I am encountering an odd problem. I am able to create and save pdf file using R/ggplot2 and view them while the R Console is running. As soon as I exit the R console, Preview on Mac OS X will no longer display the PDF. I have been able to save .png files w/o problem, but for reasons beyond my control, I need to save in pdf files. The code I am using to save is as follows:

  pdfFile <-c("/Users/adam/mock/dir/structure.pdf")
  pdf(pdfFile)
  ggplot(y=count,data=allCombined, aes(x=sequenceName, fill=factor(subClass))) + geom_bar()
  ggsave(pdfFile)  

Has anyone encountered a similar problem? If so, what do I need to do to fix it? Thank you very much for your time.

like image 880
wespiserA Avatar asked Apr 11 '11 17:04

wespiserA


People also ask

How do I save a PDF in ggplot2?

You can either print directly a ggplot into PNG/PDF files or use the convenient function ggsave() for saving a ggplot.

How do I save multiple plots as PDF in R?

To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.

What does PDF () do in R?

pdf() opens the file file and the PDF commands needed to plot any graphics requested are sent to that file. The file argument is interpreted as a C integer format as used by sprintf , with integer argument the page number. The default gives files Rplot001. pdf , …, Rplot999.


2 Answers

The problem is that you don't close the pdf() device with dev.off()

dat <- data.frame(A = 1:10, B = runif(10))
require(ggplot2)

pdf("ggplot1.pdf")
ggplot(dat, aes(x = A, y = B)) + geom_point()
dev.off()

That works, as does:

ggplot(dat, aes(x = A, y = B)) + geom_point()
ggsave("ggplot1.pdf")

But don't mix the two.

like image 163
Gavin Simpson Avatar answered Oct 14 '22 02:10

Gavin Simpson


It is in the R FAQ, you need a print() around your call to ggplot() -- and you need to close the plotting device with dev.off() as well, ie try

pdfFile <-c("/Users/adam/mock/dir/structure.pdf")
pdf(pdfFile)
ggplot(y=count,data=allCombined,aes(x=sequenceName,fill=factor(subClass)))
      + geom_bar()
dev.off()

Edit: I was half-right on the dev.off(), apparently the print() isn;t needed. Gavin's answer has more.

like image 23
Dirk Eddelbuettel Avatar answered Oct 14 '22 04:10

Dirk Eddelbuettel