[R] Using grid.layout inside grid.layout with grid package: naming of the viewports affects plotting

Helske Satu satu.helske at jyu.fi
Wed Nov 26 12:16:01 CET 2014


R version 3.1.1 (2014-07-10)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] C

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_3.1.1


I have a plotting function to produce plots with stacked plots (for simplicity, here two rectangles).

library(grid)
stackedplot <- function(main=""){
  top.vp <- viewport(
    layout=grid.layout(2, 1))
  p1 <- viewport(layout.pos.col=1, layout.pos.row=1, name="plot1")
  p2 <- viewport(layout.pos.col=1, layout.pos.row=2, name="plot2")
  splot <- vpTree(top.vp, vpList(p1,p2))
  pushViewport(splot)
  seekViewport("plot1")
  grid.rect(width=unit(0.9, "npc"), height=unit(0.9, "npc"))
  seekViewport("plot2")
  grid.rect(width=unit(0.9, "npc"), height=unit(0.9, "npc"))
 }

For creating a 2x2 grid with four stacked plots I tried to use the following code:

grid.newpage()
multitop.vp <- viewport(layout=grid.layout(2,2))
pl1 <- viewport(layout.pos.col=1, layout.pos.row=1, name="A")
pl2 <- viewport(layout.pos.col=1, layout.pos.row=2, name="B")
pl3 <- viewport(layout.pos.col=2, layout.pos.row=1, name="C")
pl4 <- viewport(layout.pos.col=2, layout.pos.row=2, name="D")
vpall <- vpTree(multitop.vp, vpList(pl1,pl2,pl3,pl4))
pushViewport(vpall)
seekViewport("A")
stackedplot(main="A")
seekViewport("B")
stackedplot(main="B")
seekViewport("C")
stackedplot(main="C")
seekViewport("D")
stackedplot(main="D")

This does not work as all the plots are plotted in the same cell of the grid (viewport A). However, if I plot them in a reversed order, the plots arrange as was supposed to: D to D, C to C and so on.

seekViewport("D")
stackedplot(main="D")
seekViewport("C")
stackedplot(main="C")
seekViewport("B")
stackedplot(main="B")
seekViewport("A")
stackedplot(main="A")

I tried with different names and found out that if I plot in reversed alphabetical order everything works fine. Once I try to plot in a viewport with a name earlier in alphabetical order, all other plots thereafter are plotted in the same viewport.

Why is this happening?

Regards,
Satu Helske

	[[alternative HTML version deleted]]



More information about the R-help mailing list