gtable_add_grob(): linesGrob() not displayed

泄露秘密 提交于 2019-12-01 10:59:41

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!