gpt4 book ai didi

r - ggplotGrob 的逆?

转载 作者:行者123 更新时间:2023-12-03 06:03:24 24 4
gpt4 key购买 nike

我有一个操作 ggplot 对象的函数,方法是将其转换为 grob,然后修改图层。我希望该函数返回 ggplot 对象而不是 grob。有没有一种简单的方法可以将 grob 转换回 gg?

The documentation 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。

这是代码,有兴趣的 friend 可以看看

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 对象是由网格定义的绘图基元。您可以从头开始创建任意对象。没有通用的方法可以将随机的 grobs 集合转回生成它们的函数(它是不可逆的,因为它不是 1:1)。一旦你走了,你就永远不会回去。

您可以将 ggplot 对象包装在自定义类中,并重载绘图/打印命令来执行一些自定义 grob 操作,但这可能更加黑客化。

关于r - ggplotGrob 的逆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com