The suggested solution works in many cases, but there's a potential pitfall to watch out for if your data is large, i.e. more than a few thousand rows. In those cases, the drawing could get very slow, and alpha
will not work as expected. But most of the time those are not significant problems.
The issue is that using geom_rect
and geom_segment
will draw one layer for every row of data, so the output of the solution has 150 rectangles, and 150 segments, drawn on top of each other. You'll note that adding alpha = 0.1
to any of these layers will look exactly the same as without it.
If this is a problem for your situation, the easiest solution would be to use annotate
instead. Compare the output of these two:
# Iris has 150 rows, so each layer gets drawn once per row
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() +
geom_rect(xmin = 5, xmax = 7, ymin = 2.5, ymax = 4, fill = NA, color = "red", alpha = 0.1) +
geom_segment(x = 5, y = 2, xend = 7, yend = 4, color = "blue", alpha = 0.1) +
geom_segment(x = 6, y = 2, xend = 7, yend = 3, color = "green", alpha = 0.1)
# annotate just draws one layer; geom_rect's alpha controls fill, so it doesn't look translucent here
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() +
annotate("rect", xmin = 5, xmax = 7, ymin = 2.5, ymax = 4, fill = NA, color = "red", alpha = 0.1) +
annotate("segment", x = 5, y = 2, xend = 7, yend = 4, color = "blue", alpha = 0.1) +
annotate("segment", x = 6, y = 2, xend = 7, yend = 3, color = "green", alpha = 0.1)