[Solved] gtable_add_grob(): linesGrob() not displayed

Why are the lines (via linesGrob) not drawn in the following plot?

require(gtable)
base <- gtable(widths=unit(rep(1, 2), "null"),
               heights=unit(rep(1, 3), "null"))
grid.newpage()
g <- 1
for(i in 1:3) {
    for(j in 1:2) {
        base <- gtable_add_grob(base,
                                grobs=list(linesGrob(x=1:4, y=4:1),
                                           rectGrob(gp=gpar(fill="#FF0000")),
                                           textGrob(label=g)), i, j, name=1:3)
        g <- g+1
    }
}
grid.draw(base)

Solution #1:

Two reasons:

  • the coordinates fall outside the viewport

  • the rectGrob is drawn on top and masks it


require(gtable)
# let's fix this name before it's too late
gtable_add_grobs <- gtable_add_grob

base <- gtable(widths=unit(rep(1, 2), "null"),
               heights=unit(rep(1, 3), "null"))
grid.newpage()
g <- 1
for(i in 1:3) {
    for(j in 1:2) {
        base <- gtable_add_grobs(base,
                                grobs=list(rectGrob(gp=gpar(fill="#FF0000")),
                                           linesGrob(x=1:4, y=4:1, def="native", 
                                                     vp=dataViewport(1:4, 1:4)),
                                           textGrob(label=g)), i, j, name=1:3)
        g <- g+1
    }
}
grid.draw(base)

Note gtable_add_grobs is vectorised, which means you shouldn’t have to use for loops, ideally. It’s easier if you group all the grobs together first, for a given cell, in a gTree. Here’s a simplified version,

library(gtable)

g <- gtable(widths = unit(c(1,1), "null"),
            heights = unit(c(1,1), "null"))


cell <- function(ii)
  grobTree(rectGrob(), 
           linesGrob(1:4, 1:4, default.units="native"), 
           textGrob(ii),
           vp=dataViewport(c(1,4), c(1,4)))

gl <- lapply(1:4, cell)

xy <- expand.grid(1:2, 1:2)

g <- gtable_add_grobs(g, gl, 
                      l=xy[,1],
                      r=xy[,1],
                      t=xy[,2],
                      b=xy[,2])


grid.newpage()
grid.draw(g)
Respondent: baptiste

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.