ggplotGrob的逆?

我有一个函数,操纵ggplot对象,通过将其转换为grob,然后修改图层。 我想这个函数返回一个ggplot对象而不是grob。 有没有一个简单的方法来将grob转换回gg?

关于ggplotGrob 的文档非常稀less。
简单的例子:

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

更新:

为了回答评论中的问题,这里的动机是基于每个方面中的标签名称的值以编程方式修改方面标签的颜色。 下面的function很好地工作(根据上一个问题的洗礼input)。

我想从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对象正在绘制由网格定义的基元。 您可以从头创build任意的grobs。 没有一种通用的方法可以把一个随机的grob集合转换成一个可以产生它们的函数(它不是可逆的,因为它不是1:1)。 一旦你去了,你永远不会回去。

你可以把一个ggplot对象封装在一个自定义的类中,然后重载plot / print命令来做一些自定义的grob操作,但是这可能更糟糕。

Interesting Posts