在ggplot2对象的现有图层下插入图层 [英] Insert Layer underneath existing layers in ggplot2 object
问题描述
例如,在下图中,可以将 geom_boxplot()
添加到 P
,这样boxplot显示在下面 geom_point()
?
##从以下开始:
library(ggplot2)
P < - ggplot(data = dat,aes(x = id,y = val)) + geom_point()
##这增加了boxplot,但掩盖了某些点
P + geom_boxplot()
预期产出:
#本质上是
ggplot(data = dat,aes(x = id,y = val))+ geom_boxplot()+ geom_point()
##然而,这涉及重新编码所有P(在新图层的点插入之后)。
##这是我希望避免的。
奖金问题:现有的情节,是否有可能指出在哪里特别插入新层(相对于现有层)?
SAMPLE DATA
set.seed(1)
N < - 100
id < - c (A,B)
dat < - data.frame(id = sample(id,N,TRUE),val = rnorm(N))
感谢@baptiste为我指出了正确的方向。要在所有其他图层下插入图层,只需修改plot对象的图层
元素即可。
##例如:
P $ layers <-c(geom_boxplot(),P $ layers)
红利回答问题:
这个方便的小函数在一个指定的z级别:
insertLayer< - function(P,after = 0,...){
#P:绘制对象
#之后:定位插入新图层的位置,相对于现有图层
#...:附加图层,用逗号(,)分隔而不是加号(+)$如果(在<0之后)
之后< - 在+长度之后(P $层)
if(!length(P $ layers))
P $ layers< - list(...)
else
P $ layers< - 追加(P $图层,列表(...),之后)
return(P)
}
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))
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)
}
这篇关于在ggplot2对象的现有图层下插入图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!