9

I'm trying to render a plot to a PDF using the following approach:

pdf('~/Desktop/test.pdf', bg = "white", paper="USr")    
p <- ggplot(df, aes(something)) + geom_bar();
print(p)
# I'm actually printing a bunch of graphs to the PDF
dev.off()

The "USr" in the PDF function is setting up the PDF to print in landscape mode. The plot is produced and is centered on the page but there is a large right/left margin and the plot isn't scaling out to take up the full 11" available to it.

I've tried some tweaks to the pdf(...) command and to the ggplot itself. Is there a solution this way or do I need to use a dedicated reporting/pdf package like sweave or knitr?

Dave
  • 1,567
  • 4
  • 13
  • 23
  • 1
    What happens when you use `ggsave( "~/Desktop/test.pdf", ... )` and specify the `width` and `height` explicitly? – Beasterfield May 01 '13 at 13:01
  • ggsave() seems to work with a height/width of 8.5/11. In order to use ggsave would I have to stitch all of my plots into one plot and then save it? I've got about 15 plots I'd like to output all to a single PDF to share. – Dave May 01 '13 at 14:26
  • Each on a single page? In this case (AFAIK) `ggsave` won't work. – Beasterfield May 01 '13 at 14:35

1 Answers1

13

See this discussion; bottom-line is you probably want to use paper=special and set width and height explicitly.

Edit:

Here's a lazy trick to use ggsave with multiple pages,

library(ggplot2)
plots = replicate(8, qplot(1,1), simplify=FALSE)
library(gridExtra)
p <- do.call(marrangeGrob, c(plots,ncol=1,nrow=1))

ggsave("multipage.pdf", p, width=11, height=8.5)

(but otherwise, pdf(...) followed by a for loop is just fine and sometimes clearer)

Community
  • 1
  • 1
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • 1
    Not lazy at all! Efficient! – TheSciGuy Mar 18 '19 at 15:02
  • FWIW, this only worked for me if I specified the arguments to `marrangeGrob` as a list: `p <- do.call(marrangeGrob, args = list(grobs = plots, ncol=1, nrow=1))`; otherwise I got a missing argument error – Von Dec 27 '19 at 18:40