3

Converting a base graph one by one to their grid equivalent using the solution with gridGraphics package (here) works without issues. However, when I try to put that in a loop I do not get the expected. Here is an example:

library(gridGraphics) 

### Make a list of 3 base plots -----
p <- vector(mode = "list", length = 3)

for (i in 1:3){
  plot(1:5^i)
  p[[i]] <- recordPlot()
}

### Attempt to convert each base plot to its grid equivalent -----
grobs <- vector(mode = "list", length = 3)

for (i in 1:3){
  plot.new() # clean up device
  p[[i]] # redraw
  # Echo graphics output using grid graphics
  grid.echo()
  # Creates a gTree object from the current grid display list
  a_gTree <- grid.grab()
  grobs[[i]] <- editGrob(grob = a_gTree, 
                         vp = viewport(width = unit(5, "cm"),
                                       height = unit(5, "cm"),
                                       angle = 90)) # rotates 90 dg
}

If I run the chunk of code inside the loop for each step I get what I need, but when I run the loop in one shot, then all grobs seems to display nothing. I feel that there is something obvious that I'm missing ...

Here is a desired output (obtained by running step by step):

cowplot::plot_grid(grobs[[1]], 
                   grobs[[2]], 
                   grobs[[3]])

enter image description here

Valentin_Ștefan
  • 6,130
  • 2
  • 45
  • 68
  • 2
    use `print(p[[i]])` in the loop . ps You can probably simplify this to `a_gTree <- grid.grabExpr(grid.echo(p[[i]]))`, and then the editGrob, to save plotting each plot again. (or all in one: `a_gTree <- grid.grabExpr(grid.echo(function() plot(1:5^i)))` – user20650 Apr 23 '18 at 19:53
  • oh boy...that was the obvious part I could't see any longer :D If you make your comment as an answer I'm happy to accept it. – Valentin_Ștefan Apr 23 '18 at 19:57

1 Answers1

2

Thanks to @user20650 to pointing out the usage of print() in the loop, so using print(p[[i]]) instead of p[[i]]. Or even better, I prefer his elegant suggestion to save some lines with using a_gTree <- grid.grabExpr(grid.echo(p[[i]])). Where grid.grabExpr captures the output from an expression without drawing anything. Also plot.new() seems optional.

for (i in 1:3){
  # Grab grid output
  a_gTree <- grid.grabExpr(grid.echo(p[[i]]))
  # Edit/modify the grob
  grobs[[i]] <- editGrob(grob = a_gTree, 
                         vp = viewport(width = unit(5, "cm"),
                                       height = unit(5, "cm"),
                                       angle = 90)) # rotates 90 dg
}
Valentin_Ștefan
  • 6,130
  • 2
  • 45
  • 68