3

I have the following R ggplot code:

require(ggplot2)
require(ggthemes)

df <- data.frame(x=1:10, y=5*(1:10))

p <- ggplot(df, aes(x,y)) +
   geom_point() +
   theme_few() +
   theme(plot.background = element_rect(fill='transparent', colour=NA), legend.position='top')

pdf('test.pdf', width=5, height=2)

plot(p)

plot(ggplot_gtable(ggplot_build(p)))

But I do get two different figures:

enter image description here

enter image description here

I like the first figure (i.e without the background grid outside panel area). However, I also need to use ggplot_build() for some other processing. Could you please help?

Soumitra
  • 189
  • 1
  • 10

1 Answers1

2

You could copy what ggplot2::print.ggplot does more directly. This seems to work.

pdf('test.pdf', width=5, height=2)

plot(p)

grid::grid.newpage()
grid::grid.draw(ggplot_gtable(ggplot_build(p)))

dev.off()
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thanks @MrFlick. Your suggestion works. Only thing is that I now get message "null device 1". Commenting dev.off() vanished the message but still solves the provlem. Do we really need it? Anyway, thanks a lot for your quick reply. – Soumitra Jan 02 '18 at 20:38
  • 1
    The message is normal and expected. Anytime you do `pdf()`, that should be followed at some point by `dev.off()` to close the document. – MrFlick Jan 02 '18 at 20:43
  • I need another help. In my actual plot I have an inset picture that I create using viewport. Could you please suggest how to apply viewport as grid.draw does not take a viewport parameter? – Soumitra Jan 04 '18 at 03:59
  • I could solve the viewport issue. It seems straightforward. `grid.newpage() grid.draw(ggplot_gtable(ggplot_build(p))) pushViewport(viewport(height=0.5, width=0.5, x=0.75, y=0.75)) grid.draw(ggplot_gtable(ggplot_build(p)))` – Soumitra Jan 05 '18 at 20:16
  • The most important thing I learnt is that if you are using grid.draw you must do the conversion `ggplot_gtable(ggplot_build(p))` instead of directly passing `p` to `grid.draw()` even when you do not need to change anything in the ggplot output `p`. – Soumitra Jan 05 '18 at 20:19
  • I was running into the same problem, awesome solution. Do you possibly have an explanation for this behaviour? – tjebo Dec 11 '18 at 23:57