【问题标题】:Insert Layer underneath existing layers in ggplot2 object在 ggplot2 对象中的现有图层下方插入图层
【发布时间】:2013-11-27 17:54:21
【问题描述】:

给定一个现有的绘图对象,是否可以在现有图层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()

预期输出:

# 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. 


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


样本数据

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

【问题讨论】:

  • 我认为这是不可能的,除非你保存最低的公共层并从那里重新混合。
  • @Maiasaura,谢谢。这就是我现在正在做的事情,但原来的 P 相当复杂,我希望避免为我需要进行的每个小修改重新编码。
  • 您可以轻松更改最终绘图中的图层顺序,p2$layers = rev(p2$layers)
  • @baptiste.. 我不想修改所有图层,但感谢您指出正确的方向!
  • 你明白了,这只是一个列表

标签: r ggplot2 layer


【解决方案1】:

感谢@baptiste 为我指明了正确的方向。要在所有其他图层下方插入一个图层,只需修改绘图对象的 layers 元素即可。

## For example:
P$layers <- c(geom_boxplot(), P$layers)

奖励问题的答案:

这个方便的小功能在指定的 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)
    }

【讨论】:

  • 这对theme() 类型元素有效吗? (我问,因为简单地添加它们是行不通的,所以我不确定你的方法是否需要对这些类型的元素控件进行细微的修改)......
【解决方案2】:

Ricardo' answer上展开,我使用下面的sn-p:

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
}

因为它允许您:

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

P - geom_boxplot()

箱线图会放在点的下方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多