4

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()
Viola
  • 487
  • 1
  • 10
  • 33

1 Answers1

3

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

G5W
  • 36,531
  • 10
  • 47
  • 80
  • How can we draw this on a plot with a colorful background? I need my rectangle to be transparent. I tried the way you suggested but it covers my plot. – Apex Oct 29 '20 at 10:02
  • @Apex Please ask a new question with a link to this question to indicate that it is a continuation. Please leave a comment here with a link to your new question. – G5W Oct 29 '20 at 12:21