我有一个操作ggplot对象的函数,方法是将其转换为grob,然后修改图层。我希望该函数返回ggplot对象而不是grob。有没有简单的方法可以将grob转换回gg?
ggplotGrob上的The documentation非常稀疏。
简单的例子:

P <- ggplot(iris) + geom_bar(aes(x=Species, y=Petal.Width), stat="identity")

G <- ggplotGrob(P)
... some manipulation to G ...

## DESIRED:
P2 <- inverse_of_ggplotGrob(G)

such that, we can continue to use basic ggplot syntax, ie
`P2 + ylab ("The Width of the Petal")`

更新:

为了回答评论中的问题,此处的动机是基于每个构面中标签名称的值,以编程方式修改构面标签的颜色。下面的功能很好地工作(基于上一个问题中洗礼的输入)。

我希望colorByGroup的返回值是ggplot对象,而不只是grob。

这是代码,适合那些有兴趣的人
get_grob_strips <- function(G, strips=grep(pattern="strip.*", G$layout$name)) {

  if (inherits(G, "gg"))
    G <- ggplotGrob(G)
  if (!inherits(G, "gtable"))
    stop ("G must be a gtable object or a gg object")

  strip.type <- G$layout[strips, "name"]
  ## I know this works for a simple
  strip.nms <- sapply(strips, function(i) {
     attributes(G$grobs[[i]]$width$arg1)$data[[1]][["label"]]
  })

  data.table(grob_index=strips, type=strip.type, group=strip.nms)
}


refill <- function(strip, colour){
  strip[["children"]][[1]][["gp"]][["fill"]] <- colour
  return(strip)
}

colorByGroup <- function(P, colors, showWarnings=TRUE) {
## The names of colors should match to the groups in facet
  G <- ggplotGrob(P)
  DT.strips <- get_grob_strips(G)

  groups <- names(colors)
  if (is.null(groups) || !is.character(groups)) {
    groups <- unique(DT.strips$group)
    if (length(colors) < length(groups))
      stop ("not enough colors specified")
    colors <- colors[seq(groups)]
    names(colors) <- groups
  }


  ## 'groups' should match the 'group' in DT.strips, which came from the facet_name
  matched_groups <- intersect(groups, DT.strips$group)
  if (!length(matched_groups))
    stop ("no groups match")
  if (showWarnings) {
      if (length(wh <- setdiff(groups, DT.strips$group)))
        warning ("values in 'groups' but not a facet label: \n", paste(wh, colapse=", "))
      if (length(wh <- setdiff(DT.strips$group, groups)))
        warning ("values in facet label but not in 'groups': \n", paste(wh, colapse=", "))
  }

  ## identify the indecies to the grob and the appropriate color
  DT.strips[, color := colors[group]]
  inds <- DT.strips[!is.na(color), grob_index]
  cols <- DT.strips[!is.na(color), color]

  ## Fill in the appropriate colors, using refill()
  G$grobs[inds] <- mapply(refill, strip = G$grobs[inds], colour = cols, SIMPLIFY = FALSE)

  G
}

最佳答案

我会说不。 ggplotGrob是一条单向街。 grob对象是由网格定义的图形基元。您可以从头开始创建任意杂项。没有通用的方法将随机的grob集合转换回会生成它们的函数(它不是可逆的,因为它不是1:1)。一旦您变得不知所措,就永远不会回去。

您可以将ggplot对象包装到自定义类中,并重载plot / print命令以执行一些自定义grob操纵,但这可能会更容易出错。

07-24 09:54