gtable_add_grob():不显示linesGrob()

时间:2013-08-03 13:54:21

标签: r r-grid gtable

为什么线条(通过linesGrob)未在下图中绘制?

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)

1 个答案:

答案 0 :(得分:5)

有两个原因:

  • 坐标位于视口之外

  • 将rectGrob绘制在顶部并屏蔽它


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)

注意 gtable_add_grobs是矢量化的,这意味着理想情况下你不必使用for循环。如果将所有grob首先组合在一起,对于给定的单元格,在gTree中,则会更容易。这是一个简化版本,

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)