Search code examples
rr-grid

How to draw rectangle using grid package


I need to draw a rectangle on my diagram to highlight different changes. I need to use grid package. I tried to use the grid.rect but it doesn't work. I want that my rectangle looks like on the picture.

On the left part of the picture you can see my diagram and of the right part of the picture I've added the rectangle (in Paint) like I want it will be.

enter image description here

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

Solution

  • It is not completely clear where you are trying to draw the rectangle, but the code below will add the rectangle to approximately match your picture. You can tune the position.

    Use your code just as you had it. I will start by repeating your print statement and then adding the rectangle.

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

    Added Rectangle