1

In R grid graphics how can I clip a grob object in a grobTree ? In a way so I would only need to call grid.draw to plot the clipped grob.

For instance when I plot my stuff directly:

# 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"))

I obtain the clipped version:

enter image description here

But when I try to put it in a grobTree object (for later manipulation), it does not work :


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

I get an unclipped version:

enter image description here

How can I have the clipped version in my grobTree object ?

1 Answers1

1

try with clip = TRUE in viewport vp