problem saving pdf file in R with ggplot2

2020-02-05 16:44发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

The following plot

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 source this 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 produce a corrupt pdf file and the way to fix it us use

print(p) 

within a function.

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



回答4:

You can also change the filename of your pdf plot within ggsave if you want to call it something other than "ggplot1" or whatever concise object name you chose; just give the filename first and then tell it which plot you're referring to, for example:

a <- ggplot(dat, aes(x = A, y = B)) + geom_point()
ggsave("Structure.pdf",plot=a)


标签: macos r ggplot2