-2

This is not a repetitive question though the title might seem similar.

Let's say I have a function f1() which plots an object of class "gTable,grob,gDesc" once. I'm using grid.draw() to plot the object.

So when we call :

pdf("filename.pdf", height = 10, weight =12)
f1()
dev.off()

This will give one page of pdf which is what i wanted.

However when i want two plots in a single pdf by the code :

pdf("filename.pdf")
f1()
f1()
dev.off()

I get is a single page pdf with just the second plot.That is the first plot was overwritten by the second. To overcome this I am using grid.newpage() but that adds one extra blank page in the pdf. How to avoid this? I can use an extra argument to create a newpage only if the argument is set. However do we have any other option?

I have played with grid.arrange() and also the onefile argument in pdf() but nothing worked.

Also when I try to plot these on the R plot window then it overwrites on the existing open graphical device. So after plotting second time, i am unable to view the first plot by using the back arrow. back arrow of R plot window

Edit : sample R code which plots an object of class "gTable, grob, gDesc"

xxx <- function(){
set.seed(1111)
dd <- diamonds[sample(1:nrow(diamonds), 1000, replace = TRUE), ]
dd$color <- sample(letters[1:2], 1000, replace = TRUE)

p  <- ggplot(data = dd, aes(x = cut))  
p1 <- p + geom_bar(fill = "orange", alpha = 1) + facet_wrap(~color)+
          ggtitle("Main title")+scale_y_continuous("frequency", expand = c(0, 0))+
          labs(x = "cut", y = "frequency")+
          theme(panel.background = element_rect(colour = "white"),
                axis.text.x = element_text(angle = 45, hjust = 1),
                panel.grid.major = element_blank(),
                panel.grid.minor = element_blank(),
               legend.position = "bottom") 

  p2 <- p + geom_line(aes(y = price), alpha = 0)+
            labs(x = "", y = "price")+expand_limits(y = 0) +
            stat_summary(aes(y = price, group = 1, colour = "mean"), fun.y = "mean", geom = c("point"))+ 
            stat_summary(aes(y = price, group = 1, colour = "mean"), fun.y = "mean", geom = c("line"))+ 
            stat_summary(aes(y = price, group = 1, colour = "median"), fun.y = "median", geom = "point")+
            stat_summary(aes(y = price, group = 1, colour = "median"), fun.y = "median", geom = "line")+
            scale_colour_manual(name = "" ,breaks = c("mean", "median"), values = c("red", "blue"))+
            facet_wrap(~color)+ylab("Exposures")+
            theme(panel.background = element_rect(fill = NA, colour = "white"),
                  panel.grid.major = element_blank(),
                  panel.grid.minor = element_blank(),
                  panel.border = element_rect(fill = NA, colour = "grey50"),
                  legend.position = "bottom") 

  xx <- ggplot_build(p1)
  yy <- ggplot_build(p2)

  nrow <- length(unique(xx$panel$layout$ROW))
  ncol <- length(unique(xx$panel$layout$COL))
  npanel <- length(xx$panel$layout$PANEL)

  g1 <- ggplot_gtable(xx)
  g2 <- ggplot_gtable(yy)

  pp <- c(subset(g1$layout, grepl("panel", g1$layout$name), se = t:r))
  g <- gtable_add_grob(g1, g2$grobs[grepl("panel", g1$layout$name)], 
                       pp$t, pp$l, pp$b, pp$l)

  func1 <- function(grob){
        widths <- grob$widths
        grob$widths[1] <- widths[3]
        grob$widths[3] <- widths[1]
        grob$vp[[1]]$layout$widths[1] <- widths[3]
        grob$vp[[1]]$layout$widths[3] <- widths[1]

        grob$children[[1]]$hjust <- 1 - grob$children[[1]]$hjust 
        grob$children[[1]]$vjust <- 1 - grob$children[[1]]$vjust 
        grob$children[[1]]$x <- unit(1, "npc") - grob$children[[1]]$x
        grob
     }


  index <- which(g2$layout$name == "ylab") 
  ylab <- g2$grobs[[index]]                # Extract that grob
  ylab <- func1(ylab) 
  ylab$children[[1]]$rot <- ylab$children[[1]]$rot + 180
  g <- gtable_add_cols(g, g2$widths[g2$layout[index, ]$l], pos = max(pp$r))
  g <-gtable_add_grob(g,ylab, t = min(pp$t), l = max(pp$r)+1, 
                      b = max(pp$b), r = max(pp$r)+1,
                      clip = "off", name = "2ndylab")

  j = 1
  k = 0

  for(i in 1:npanel){ 
    if ((i %% ncol == 0) || (i == npanel)){
      k = k + 1
      # swap the 2nd y-axis label

     index <- which(g2$layout$name == "axis_l-1")  # Which grob
     yaxis <- g2$grobs[[index]]                    # Extract the grob
     ticks <- yaxis$children[[2]]
      ticks$widths <- rev(ticks$widths)
     ticks$grobs <- rev(ticks$grobs)
     ticks$grobs[[1]]$x <- ticks$grobs[[1]]$x - unit(1, "npc")
     ticks$grobs[[2]] <- func1(ticks$grobs[[2]])
     yaxis$children[[2]] <- ticks
     if ((k == 1) || ((i == npanel) & (i%%ncol != 0)))#to ensure just once d secondary axisis printed 
      g <- gtable_add_cols(g,g2$widths[g2$layout[index,]$l], max(pp$r[j:i]))
      g <- gtable_add_grob(g,yaxis,max(pp$t[j:i]),max(pp$r[j:i])+1, max(pp$b[j:i])
                       , max(pp$r[j:i]) + 1, clip = "off", name = "2ndaxis")
     j = i + 1
  }
}

 pp <- c(subset(g2$layout, name == "guide-box", se = t:r))
 g <- gtable_add_grob(g, g2$grobs[[which(g2$layout$name == "guide-box")]], t = pp$t, 
                   l = pp$r, b = pp$b, r = pp$r )
 grid.draw(g)
}

This is a sample function. So if I call the following code:

pdf("zzz.pdf")
xxx()
xxx()
dev.off()

Only a single page pdf is created in above case. And if you simply call

xxx()
xxx()

Then in the R plot window Ican just view the second plot. The back arrow button is disabled since the first plot was overwritten.

joel.wilson
  • 8,243
  • 5
  • 28
  • 48

1 Answers1

1

The solution is to use grid.newpage() after the first plot,

 xxx <- function() {gg <- ggplotGrob(ggplot()); grid.draw(gg)}

 pdf("zzz.pdf")
 xxx()
 grid.newpage()
 xxx()
 dev.off()

enter image description here

You may find it easier to have the function return a grob rather than drawing it, and define a print/draw method for a list of such objects to be displayed. See gridExtra:::print.arrangelist for such a strategy,

xxx <- function() {gg <- ggplotGrob(ggplot()); gg}

plots <- marrangeGrob(replicate(3, xxx(), simplify = FALSE), nrow=1, ncol=1)
pdf("zzz.pdf")
print(plots)
dev.off()

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294
  • thanks for this. I'm aware of this one. This will solve my first query but would to know how to solve the second issue. If we compare the Base R plot() function, we can access the previous plots on R plot window using the beck arrow button. However whle working with this object it overwrites on each other. – joel.wilson Jul 29 '16 at 16:26
  • the interactive behaviour is probably device-dependent (or IDE) – baptiste Jul 29 '16 at 21:44