Given an Existing plot object is it possible to add a layer UNDERNEATH an existing layer?
Example, in the graph below, is it possible to add geom_boxplot()
to P
such that the boxplot appears underneath geom_point()
?
## Starting from:
library(ggplot2)
P <- ggplot(data=dat, aes(x=id, y=val)) + geom_point()
## This adds boxplot, but obscures some of the points
P + geom_boxplot()
Expected Output:
# Which is essentially
ggplot(data=dat, aes(x=id, y=val)) + geom_boxplot() + geom_point()
## However, this involves re-coding all of P (after the point insertion of the new layer).
## which is what I am hoping to avoid.
Bonus question: If there are multiple layers in the existing plot, is it possible to indicate where specifically to insert the new layer (with respect to the existing layers)?
SAMPLE DATA
set.seed(1)
N <- 100
id <- c("A", "B")
dat <- data.frame(id=sample(id, N, TRUE), val=rnorm(N))
P
is rather involved, and I am hoping to avoid recoding it for each small modification I need to produce. – Sayerp2$layers = rev(p2$layers)
– Bicarb