如何将 grob 剪辑到 grobTree 对象中

How to clip a grob into a grobTree object

在 R 网格图形中,如何在 grobTree 中剪切 grob 对象?在某种程度上,我只需要调用 grid.draw 来绘制剪裁的 grob。

例如,当我直接绘制我的东西时:

# Direct plotting ----

library(grid)

grid.newpage()
vp <- viewport(x = 0.25, y = 0.25, width = 0.5,height = 0.5,
               just = c("left", "bottom"), name = "vp")
pushViewport(vp)

grid.rect()
grid.polygon(x = c(0.4,0.9, 1.4, 0.9), y = c(0.5, 0.75, 0.5, 0.25), 
             gp = gpar(lty = 3))

grid.clip()

grid.polygon(x = c(0.4,0.9, 1.4, 0.9), y = c(0.5, 0.75, 0.5, 0.25), 
             gp = gpar(fill = "grey"))

我获取了剪辑版本:

但是当我尝试将其放入 grobTree 对象(以供以后操作)时,它不起作用:


# Indirect plotting ----

library(grid)

aGrob <- grobTree()

vp <- viewport(x = 0.25, y = 0.25,,width = 0.5,,height = 0.5,
               just = c("left", "bottom"), name = "vp")

r1 <- rectGrob(vp = vp)
p1 <- grid.polygon(x = c(0.4,0.9, 1.4, 0.9), y = c(0.5, 0.75, 0.5, 0.25), 
                   gp = gpar(lty = 3), vp = vp)

c1 <- clipGrob(vp = vp)

p2 <- grid.polygon(x = c(0.4,0.9, 1.4, 0.9), y = c(0.5, 0.75, 0.5, 0.25), 
                   gp = gpar(fill = "grey"), vp = vp)

aGrob <- grobTree(aGrob, r1, p1, c1, p2)

grid.newpage()

grid.draw(aGrob)

我得到一个未剪辑的版本:

我怎样才能在我的 grobTree 对象中得到剪辑版本?

在视口 vp

中尝试使用 clip = TRUE