[R] Problems outputting ggplot2 graphics to pdf

Duncan Murdoch murdoch.duncan at gmail.com
Thu Mar 2 14:46:35 CET 2017


On 02/03/2017 8:37 AM, Hugh Morgan wrote:
> 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,

ggplot2 graphics only appear when they are printed.  By default 
source("test.R") won't print anything.  Set print.eval = TRUE (or echo = 
TRUE) to get it to print.

Duncan Murdoch



More information about the R-help mailing list