This is a follow-up question to my previous question on how to shade regions of a plot based on whether a given condition is satisfied or not.
When adding several geom_*
layers to a ggplot2
plot, the layers are apparently drawn, by default, in the order in which they are added to the plot. For instance, in my answer to my previous question, a semi-transparent geom_rect()
layer is added after a geom_line()
layer. As a result, the line color changes slightly where the rectangles are overlaid; this is particularly evident when zooming in:
I would like to avoid this by putting the geom_rect()
layer behind (below) the geom_line()
layer.
The obvious solution is to add the layers in that order, that is, ggplot(...) + geom_rect(...) + geom_line()
. This would work in the artificial example from my previous question.
In my actual, real-world application, however, this is not so easy. I have a relatively complicated plot, and several different sets of conditions I want to use for highlighting periods in said plot by shading them. What I'm doing thus is to
- create the (complicated) plot without any shading,
- save it to a variable (say
g
), and then, for each set of conditions that I want to highlight separately, - perform
g + geom_rect(...) + scale_fill_discrete(...)
to add the required shading.
Adding geom_rect(...)
before the remaining layers would require me to recreate the complicated plot in question for each new version with different highlighting, and I would prefer to avoid that.
It seems to me that the obvious answer would be to explicitly tell ggplot2
the Z order of the layers, something along the lines of e.g. ggplot(...) + geom_line(z.order = 0, ...) + geom_rect(z.order = -1, ...)
in my artificial example. But I don't know how to do this, or whether it is even possible. I've searched Google and StackOverflow for a solution, but found nothing really helpful, beyond some suggestions that this may in fact not be possible using current ggplot2
versions.
Any help would be greatly appreciated. As always, thank you!