问题
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))
回答1:
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)
}
回答2:
As shown in the ggplot documentation here, you can set up a skeleton ggplot object and add layers. The order in which you specify the layers is the order in which they will appear on your plot.
This will get your expected output:
ggplot() +
geom_boxplot(data = dat, aes(x=id, y=val)) +
geom_point(data = dat, aes(x=id, y=val))
This will get your incorrect output:
ggplot() +
geom_point(data = dat, aes(x=id, y=val)) +
geom_boxplot(data = dat, aes(x=id, y=val))
I think this answers your bonus question too :)
来源:https://stackoverflow.com/questions/20249653/insert-layer-underneath-existing-layers-in-ggplot2-object