Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

widths not adhered to when using grid.layout

Tags:

r

layout

r-grid

I'm trying to create a layout similar to

Example layout

But whatever I set for the widths the layout keeps using the full width of the panel for Plot with the following code:

masterLayout <- grid.layout(
    nrow    = 4,
    ncol    = 1,
    widths  = c(1,0.6,1,1),
    heights = c(.2,.6,.1,.1))

vp1 <- viewport(layout.pos.row=1, name="title")
vp2 <- viewport(layout.pos.row=2, name="plot")
vp3 <- viewport(layout.pos.row=3, name="legend")
vp4 <- viewport(layout.pos.row=4, name="caption")

pushViewport(vpTree(viewport(layout = masterLayout, name = "master"),
                    vpList(vp1, vp2, vp3, vp4)))

How can I replicate the layout in the image using the grid package?

like image 334
JoelKuiper Avatar asked Mar 14 '23 20:03

JoelKuiper


2 Answers

grid.layout makes a rectangular table, so for a given column (row) all widths (resp. heights) will be equal. Your approach of pushing a viewport of specific dimensions inside the cell is probably the easiest.

As an alternative approach, you could make a layout with more columns, and specify which range of cells to use for a specific grob.

library(gridExtra)

gs <- lapply(1:4, function(ii) 
  grobTree(rectGrob(gp=gpar(fill=ii, alpha=0.5)), textGrob(ii)))

m <- rbind(c(1,  1,  1), 
           c(NA, 2, NA),
           c(3,  3,  3), 
           c(4,  4,  4))
grid.arrange(grobs = gs, 
             layout_matrix = m,
             heights=unit(c(1,1,1,1), c("line", "null", "line")),
             widths = unit(c(0.2,0.6,0.2), "npc"))

enter image description here

like image 53
baptiste Avatar answered Mar 17 '23 15:03

baptiste


So one way to fix this is to push another viewport when drawing the plot viewport

seekViewport("plot")
pushViewport(viewport(width=unit(0.8, "npc")))
... plot ...
popViewport()
... continue as usual

But it's still strange that widths does not work, or am I misinterpreting that argument?

like image 39
JoelKuiper Avatar answered Mar 17 '23 15:03

JoelKuiper