1

I am trying to add four transparent bands to my ggplot for the following y ranges:

  • y<2 & y>1.5
  • y<1.5 & y>1
  • y<1 & y>0.5
  • y<0.5 & y>0

I don't want the ranges to overlap as that changes the colour that I'm assigning each band (as they're transparent).

I can sort of get the effect I'm after using geom_area (see code below), but they overlap, which changes the colour.

I'm wondering if there is a better way to get the bands specifically in the areas I want?

 df <- data.frame(y1=rep(1.99, 100),
                  y2=rep(1.49, 100),
                  y3=rep(0.99, 100),
                  y4=rep(0.49, 100),
                  x =1:100)

 ggplot(aes(x=x), data = df) + 
   geom_area(aes(y=ifelse(y1<2 & y1>1.5, y1, 0)), data=df, fill="yellow", alpha = 0.3) +
   geom_area(aes(y=ifelse(y2<1.5 & y2>1, y2, 0)), data=df, fill="darkgoldenrod1", alpha = 0.3) +
   geom_area(aes(y=ifelse(y3<1 & y3>0.5, y3, 0)), data=df, fill="darkorange1", alpha = 0.3) +
   geom_area(aes(y=ifelse(y4<0.5 & y4>0, y4, 0)), data=df, fill="darkred", alpha = 0.3) +
   theme_classic()

Also, potentially separate question, is there a way to make the fill color go all the way to the axis rather than just leaving a white buffer space around it?

M--
  • 25,431
  • 8
  • 61
  • 93
morgan121
  • 2,213
  • 1
  • 15
  • 33

1 Answers1

1

Use geom_rect before plotting any points

ggplot() + 
  geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 1.5, ymax = 2), fill="yellow", alpha = 0.3) +
  geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 1, ymax = 1.5), fill="darkgoldenrod1", alpha = 0.3) +
  geom_point(data = df, aes(x = x, y = y1)) +
  theme_classic()

See geom_rect and alpha - does this work with hard coded values? for getting alpha to work correctly with the rectangles.

qwr
  • 9,525
  • 5
  • 58
  • 102