gpt4 book ai didi

r - 将构面标签更改为 ggplot2 中的数学公式

转载 作者:行者123 更新时间:2023-12-02 18:19:33 26 4
gpt4 key购买 nike

我想知道如何将facet标签更改为ggplot2中的数学公式。

d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) + stat_binhex(na.rm = TRUE) + opts(aspect.ratio = 1)
d + facet_wrap(~ color, ncol = 4)

enter image description here

例如,我想将构面标签从 D 更改为 Y[1],其中 1 是下标。预先感谢您的帮助。

我找到了这个answer但这对我不起作用。我正在使用 R 2.15.1ggplot2 0.9.1

最佳答案

您可以在 gtable 中编辑 grobs,

ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) + stat_binhex(na.rm = TRUE) + facet_wrap(~ color, ncol = 4)


for(ii in 1:7)
grid.gedit(gPath(paste0("strip_t-", ii), "strip.text"),
grep=TRUE, label=bquote(gamma[.(ii)]))

enter image description here

或者,如果你想保存一个grob,

g <- ggplotGrob(d)
gg <- g$grobs

strips <- grep("strip_t", names(gg))
for(ii in strips)
gg[[ii]] <- editGrob(getGrob(gg[[ii]], "strip.text",
grep=TRUE, global=TRUE),
label=bquote(gamma[.(ii)]))

g$grobs <- gg

使用 ggsave 需要额外的(丑陋的)工作,因为必须愚弄 ggplot 类的测试...我认为调用 pdf() 会更容易;网格.绘制(g); dev.off() 明确地。

<小时/>

罗兰编辑:

我做了一个小修正并将其包装在一个函数中:

facet_wrap_labeller <- function(gg.plot,labels=NULL) {
#works with R 3.0.1 and ggplot2 0.9.3.1
require(gridExtra)

g <- ggplotGrob(gg.plot)
gg <- g$grobs
strips <- grep("strip_t", names(gg))

for(ii in seq_along(labels)) {
modgrob <- getGrob(gg[[strips[ii]]], "strip.text",
grep=TRUE, global=TRUE)
gg[[strips[ii]]]$children[[modgrob$name]] <- editGrob(modgrob,label=labels[ii])
}

g$grobs <- gg
class(g) = c("arrange", "ggplot",class(g))
g
}

这样可以很好地打印,甚至可以使用ggsave

关于r - 将构面标签更改为 ggplot2 中的数学公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979017/

26 4 0