2

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)
4

1 回答 1

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 循环。如果您首先将所有 grobs 组合在一起,对于给定的单元格,在 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)
于 2013-08-03T14:01:06.903 回答