11

I am trying to make a plot in R that has a portion of the plot grey to emphasize this area. Unlike other examples, I don't want to color an area under a plot, but instead color an area on a plot starting at one area and going to the end of the graph. When I try to use rect() or polygon() it obscures the plots I want to emphasize.

For example:

x_mean <- c(1, 2, 3, 4)
y_mean <- c(1, 1, 1, 1)

y_max <- c(4, 4, 4, 4)
y_min <- c(-4, -4, -4, -4)


x_shade <- c(2, 3, 4)

y_max_shade <- c(4, 4, 4)
y_min_shade <- c(-4, -4, -4)

plot(x=rep(x_mean, 3), y=c(y_mean, y_max, y_min), bty='n', type="n" )
arrows(x0=x_mean, y0=y_min, x1=x_mean, y1=y_max, length=0)
points( x=x_mean, y=y_mean, pch=16)

This will plot 4 lines on the graph. How do I draw a grey box in the background from the 2nd line to the end of the plot?

Kevin
  • 1,112
  • 2
  • 15
  • 29
  • 5
    R graphics uses a pen+paper model, which means objects drawn later are drawn _on top of_ earlier objects. Try plotting with `rect()` first, and then drawing the points and lines you want. – joran Jun 28 '12 at 17:26

2 Answers2

16

Just so that you're left with more than just a comment, here's a possible solution:

plot(x=rep(x_mean, 3), y=c(y_mean, y_max, y_min), bty='n', type="n" )
rect(2,-4,4,4,col = rgb(0.5,0.5,0.5,1/4))
arrows(x0=x_mean, y0=y_min, x1=x_mean, y1=y_max, length=0)
points( x=x_mean, y=y_mean, pch=16)

enter image description here

Note that I also demonstrated how to use alpha blending in the color specification (using rgb). This can also be useful for this sort of thing. Try moving the rect line to the end, and notice that the results still look ok, because the fill color is partially transparent.

joran
  • 169,992
  • 32
  • 429
  • 468
2

I've found this answer to be pretty great for shading background parts of R.

Some context:

panel.first = rect(c(1,7), -1e6, c(3,10), 1e6, col='green', border=NA)

The first two arguments c(1,7) are the starting values for the shaded rectangle, and following arguments c(3,10) are where the shading ends. This creates a shaded region from 1-3 and 7-10.