[ACCEPTED]-problem saving pdf file in R with ggplot2-ggplot2

Accepted answer
Score: 31

The problem is that you don't close the 2 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 1 mix the two.

Score: 6

It is in the R FAQ, you need a print() around your 4 call to ggplot() -- and you need to close the plotting 3 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 2 on the dev.off(), apparently the print() isn;t needed. Gavin's 1 answer has more.

Score: 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 6 but not in a function or when you source 5 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 4 pdf file and the way to fix it us use

print(p) 

within 3 a function.

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

More Related questions