How to use R base plots in grid.newpage?

2019-02-13 16:54发布

问题:

Is it possible to "force" R base plots in grid package's grid.newpage? For example, this works fine:

library(grid)
grid.newpage()
vp1 <- viewport(x=0,y=0.5,width=0.5, height=0.5, just = c("left", "bottom"))
vp2 <- viewport(x=0.5,y=0,width=0.5, height=0.5, just = c("left", "bottom"))
pushViewport(vp1)
grid.rect()
grid.text("vp1", 0.5, 0.5)
upViewport()
pushViewport(vp2)
grid.rect()
grid.text("vp2", 0.5, 0.5)

.

But if I try something like this:

grid.newpage()
vp1 <- viewport(x=0,y=0.5,width=0.5, height=0.5, just = c("left", "bottom"))
vp2 <- viewport(x=0.5,y=0,width=0.5, height=0.5, just = c("left", "bottom"))
pushViewport(vp1)
grid.rect()
print(plot(1,2))
grid.text("vp1", 0.5, 0.5)
upViewport()
pushViewport(vp2)
grid.rect()
print(plot(1,2))

R base plot just over-rides grid.newpage. Using par(new=T) does not help either.

回答1:

Because no-one answered this, I'll do it myself. As Andrie said, the answer to this question is here. You'll need gridFIG()function from gridBase package to plot R base plots in plot.new() instead of grid.newpage():

library(grid)
library(gridBase)
plot.new()
vp1 <- viewport(x=0,y=0.5,width=0.5, height=0.5, just = c("left", "bottom"))
vp2 <- viewport(x=0.5,y=0,width=0.5, height=0.5, just = c("left", "bottom"))
pushViewport(vp1)
grid.rect()
grid.text("vp1", 0.5, 0.5)
par(new=TRUE, fig=gridFIG())
plot(1,2)
upViewport()
pushViewport(vp2)
grid.rect()
grid.text("vp2", 0.5, 0.5)
par(new=TRUE, fig=gridFIG())
plot(1,2)



标签: r plot r-grid