如何使用网格包绘制矩形

How to draw rectangle using grid package

我需要在图表上画一个矩形来突出显示不同的变化。我需要使用 grid 包。我尝试使用 grid.rect 但它不起作用。我希望我的矩形看起来像图片上的那样。

在图片的左侧,您可以看到我的图表,在图片的右侧,我添加了我想要的矩形(在 Paint 中)。

library(grid)
library(lattice)
library(sandwich)

data("Investment")
Investment <- as.data.frame(Investment)

trellis.par.set(theme = canonical.theme("postscript", color=FALSE))
grid.newpage()
pushViewport(viewport(x=0, width=.4, just="left"))
print(barchart(table(Investment$Interest)),
  newpage=FALSE)
popViewport()
pushViewport(viewport(x=.4, width=.5, just="left"))
print(xyplot(Investment ~ Price, data=Investment, 
         auto.key=list(space="right"),
         par.settings=list(superpose.symbol=list(pch=c(1, 3, 16),
                             fill="white"))),
  newpage=FALSE)

popViewport()

尚不完全清楚您要在何处绘制矩形,但下面的代码将添加矩形以大致匹配您的图片。你可以调整位置。

按原样使用您的代码。我将首先重复您的打印语句,然后添加矩形。

print(xyplot(Investment ~ Price, data=Investment, 
         auto.key=list(space="right"),
         par.settings=list(superpose.symbol=list(pch=c(1, 3, 16),
                             fill="white"))),
  newpage=FALSE)


grid.rect(x = unit(0.42, "npc"), y = unit(0.35, "npc"),
          width = unit(0.2, "npc"), height = unit(0.2, "npc"),
        gp=gpar(col="red"))

popViewport()