ggplotGrob的反函数是什么?

56

我有一个函数,它通过将ggplot对象转换为grob并修改图层来进行操作。我希望该函数返回一个ggplot对象而不是grob。有没有一种简单的方法将grob转换回gg?

ggplotGrob 的文档非常稀少。
下面是一个简单的例子:

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")`

更新:

回答评论中的问题,这里的动机是根据每个分面标签名称的值,在程序上修改分面标签的颜色。以下函数效果很好(基于之前问题中baptise的输入)。

我希望从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
}
3个回答

15

我认为不行。ggplotGrob是单向的。 grob对象是由网格定义的绘图原语。您可以从头开始创建任意grobs。没有一般方法将随机收集的grobs转换回生成它们的函数(它不可逆,因为不是1:1)。一旦您使用grob,就再也不能回去了。

您可以在自定义类中包装ggplot对象,并重载plot / print命令以进行某些自定义grob操作,但这可能更加hack-ish。


6

as.ggplot() 不会将 grob 转换为 ggplot 对象。它只能将一个 plot 转换为 ggplot。 - Yoann Pageaud

3

请查看ggpubr包:它有一个名为as_ggplot()的函数。如果您的grobs不太复杂,这可能是一个解决方法!

我也建议查看patchwork包,它可以很好地组合ggplots...尽管可能不符合您的需求,但还是要看一下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接