Last active
April 8, 2019 17:49
-
-
Save dhicks/3571d32fac0495c34a6f6570bfdb2142 to your computer and use it in GitHub Desktop.
Shade rectangular areas of a ggplot plot across facets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## It took me three days to find this solution! | |
## <https://stackoverflow.com/questions/44688623/adding-custom-images-to-ggplot-facets/44897816#44897816> | |
annotation_custom2 <- function (grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, data) | |
{ | |
layer(data = data, stat = StatIdentity, position = PositionIdentity, | |
geom = ggplot2:::GeomCustomAnn, | |
inherit.aes = FALSE, params = list(grob = grob, | |
xmin = xmin, xmax = xmax, | |
ymin = ymin, ymax = ymax)) | |
} | |
rects = tibble( | |
Species = c('setosa', 'versicolor', 'virginica'), | |
low = c(-1, 1.5, 2), | |
high = c(1, 2, 3), | |
fill = c(.1, .2, .3) | |
) %>% | |
mutate(grob = pmap(list(low, high, fill, Species), | |
~ annotation_custom2(grid::rectGrob(gp = grid::gpar(fill = 'black', alpha = ..3)), | |
xmin = -Inf, xmax = Inf, | |
ymin = ..1, ymax = ..2, | |
data = tibble(Species = ..4)))) | |
p = ggplot(iris, aes(Species, Petal.Width)) + | |
geom_point() + | |
facet_wrap(~ Species) + | |
coord_flip() | |
p + rects$grob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment