1

I want to make a boxplot with a horizontal rectangle behind the plots (or above with opacity). I am not sure how to do this with categorical x-axis values and force it to extend the entire width of the plot area. This answer was helpful, but I'm not sure how to extend the rectangle to the edges of the plot area.

Let's say we want to make a rectangle across the diamonds cuts between $3000 and $5000. I have attempted the code below, but it doesn't extend to the edge of the plot.

rectangle <- data.frame(x = c("Fair","Good","Very good", "Premium", "Ideal"), 
                    lower = rep(3000, 5),
                    upper = rep(5000, 5))
ggplot() +
  geom_boxplot(data=diamonds, aes(x=cut, y=price)) +
  geom_rect(data=rectangle, aes(xmin="Fair", xmax="Ideal", 
                                ymin=lower, ymax=upper), alpha=0.1)

Output

boxplot with rectangle

oatmilkyway
  • 429
  • 1
  • 6
  • 17

1 Answers1

2

To get the rectangle to the panel edges you can set the limits as +/-Inf.

Also for a single rectangle like this (and not mapping any aesthetics) it may be worth just using annotate:

annotate("rect", xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000, alpha=0.4)

but for completeness, you can still use a geom_rectcall

geom_rect(aes(xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000), alpha=0.4)

You can move the rectangle behind the boxplots by changing the order of the geoms.

ggplot(diamonds, aes(x=cut, y=price)) +
    geom_blank() +
    annotate("rect", xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000) +
    geom_boxplot()
user20650
  • 24,654
  • 5
  • 56
  • 91