Problem saving a PDF file to R using ggplot2

I ran into an odd problem. I can create and save a 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 file. I was able to save .png files without problems, but for reasons beyond my control, I need to save the files in pdf format. The code I use 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 this? Thank you so much for your time.

+10
r ggplot2 macos
Apr 11 2018-11-11T00:
source share
4 answers

The problem is that you are not closing 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() 

This works like:

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

But do not mix them.

+30
Apr 11 2018-11-11T00:
source share

In the Frequently Asked Questions section, you need print() around your ggplot() call - and you also need to close the build device with dev.off() , i.e. to 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 dev.off() , apparently print() isn; t. Gavin's answer is more.

+5
Apr 11 2018-11-11T00:
source share

Next chart

 pdf("test.pdf") p <- qplot(hp, mpg, data=mtcars, color=am, xlab="Horsepower", ylab="Miles per Gallon", geom="point") p dev.off() 

works in the console, but not in a function or when you send it from a file.

 myfunc <- function() { p <- qplot(hp, mpg, data=mtcars, color=am, xlab="Horsepower", ylab="Miles per Gallon", geom="point") p } pdf("test.pdf") myfunc() dev.off() 

Will create a damaged pdf file and a way to fix it.

 print(p) 

inside the function.

In the console. "p" is automatically printed, but not in the function or in the source file.

0
Mar 18 '17 at 15:43
source share

You can also change the file name of your pdf-graphic in ggsave if you want to call it something other than "ggplot1" or any short name of the object that you have chosen; just specify the file name first, and then tell which story you are referring to, for example:

 a <- ggplot(dat, aes(x = A, y = B)) + geom_point() ggsave("Structure.pdf",plot=a) 
-one
03 Oct '14 at 16:15
source share



All Articles