在ggplot2对象中的现有图层下插入图层

Ric*_*rta 23 r layer ggplot2

鉴于现有的剧情对象是有可能添加层UNDERNEATH现有图层?

例如,在下面的图表中,是有可能添加geom_boxplot()P使得出现箱线图下方 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()
Run Code Online (Sandbox Code Playgroud)

预期产出:

# 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. 
Run Code Online (Sandbox Code Playgroud)

示例输出


额外问题: 如果现有图中有多个图层,是否可以指示插入新图层的具体位置(相对于现有图层)?


样本数据

set.seed(1)
N <- 100
id <- c("A", "B")
dat <- data.frame(id=sample(id, N, TRUE), val=rnorm(N))
Run Code Online (Sandbox Code Playgroud)

Ric*_*rta 36

谢谢@baptiste指出我正确的方向.要在所有其他图层下插入图层,只需修改layers绘图对象的元素即可.

## For example:
P$layers <- c(geom_boxplot(), P$layers)
Run Code Online (Sandbox Code Playgroud)

回答奖金问题:

这个方便的小函数在指定的z级别插入一个层:

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)
    }
Run Code Online (Sandbox Code Playgroud)


kra*_*ski 8

扩展里卡多的答案,我使用以下代码片段:

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
}
Run Code Online (Sandbox Code Playgroud)

因为它允许您:

P <- ggplot(data=dat, aes(x=id, y=val)) + geom_point()

P - geom_boxplot()
Run Code Online (Sandbox Code Playgroud)

箱线图将放置在点下方。