Insert Layer underneath existing layers in ggplot2 object
Expanding on Ricardo' answer, I use the following snippet:
library(ggplot2)
`-.gg` <- function(plot, layer) {
if (missing(layer)) {
stop("Cannot use `-.gg()` with a single argument. Did you accidentally put - on a new line?")
}
if (!is.ggplot(plot)) {
stop('Need a plot on the left side')
}
plot$layers = c(layer, plot$layers)
plot
}
As it allows you to:
P <- ggplot(data=dat, aes(x=id, y=val)) + geom_point()
P - geom_boxplot()
And the boxplot will be placed below the points.
Thanks @baptiste for pointing me in the right direction. To insert a layer underneath all other layers, just modify the layers
element of the plot object.
## For example:
P$layers <- c(geom_boxplot(), P$layers)
Answer to the Bonus Question:
This handy little function inserts a layer at a designated z-level:
insertLayer <- function(P, after=0, ...) {
# P : Plot object
# after : Position where to insert new layers, relative to existing layers
# ... : additional layers, separated by commas (,) instead of plus sign (+)
if (after < 0)
after <- after + length(P$layers)
if (!length(P$layers))
P$layers <- list(...)
else
P$layers <- append(P$layers, list(...), after)
return(P)
}