[R] Problems outputting ggplot2 graphics to pdf

Hugh Morgan h.morgan at har.mrc.ac.uk
Thu Mar 2 14:37:53 CET 2017


Hi All,

I am having trouble outputting ggplot2 graphics to pdf as part of a
script.  It works if when I pipe the script into R or if I type the
commands directly into the terminal, but not if I load it using the
source(..) command.  In this case the outputted pdf is always size 3611,
and it fails to open with the error "This document contains no pages".

As an example I wrap the create pdf commands around the 1st example in
?ggplot:

$ cat test.R

library(ggplot2)

pdf("test.pdf")

df <- data.frame(
   gp = factor(rep(letters[1:3], each = 10)),
   y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(gp, y)) +
   geom_point() +
   geom_point(data = ds, aes(y = mean), colour = 'red', size = 3)

dev.off()

Piping it into R works:

$ R --no-save < test.R

...

$ ll test.pdf

-rw-rw-r-- 1 user group 4842 Mar  2 13:18 test.pdf

This file opens fine and has a graphic.  If I repeat the process using
source():

$ R --no-save

R version 3.3.2 (2016-10-31) -- "Sincere Pumpkin Patch"
...

 > source("test.R")
 >

$ ll test.pdf
-rw-rw-r-- 1 user group 3611 Mar  2 13:25 test.pdf

This file fails to open, and always has the size 3611.

Any help appreciated,

Hugh



This email may have a PROTECTIVE MARKING, for an explanation please see: http://www.mrc.ac.uk/About/Informationandstandards/Documentmarking/index.htm



More information about the R-help mailing list