如何使用网格编辑ggplot2对象以将数学表达式添加到facet标签? [英] How can I use grid to edit a ggplot2 object to add math expressions to facet labels?
问题描述
我需要使用ggplot2中的facet_wrap()将希腊字母放到facet标签中。我发现一个描述facet_grid()的链接。我使用以下代码将其应用于我的数据:
I need to put Greek letters into facet labels using facet_wrap() in ggplot2. I found a Link describing the same for facet_grid(). I applied this for my data, using the following code:
levels(parameters) <- c(expression(alpha), expression(beta))
p + facet_grid(.~parameters, labeller = label_parsed)
伟大的工作,并做我想要的。但是,我需要使用facet_wrap()来代替(为两个参数获取单独的y轴,并且还要在不同的列和行中绘制更多的参数)。我尝试了以下方法:
This works great and does exactly what I want. However, I need to use facet_wrap() instead (to get separate y-axes for both paramters, and also to plot even more parameters in different columns and rows). I tried the following:
p + facet_wrap(.~parameters, labeller = label_parsed) , or
p + facet_wrap(.~parameters)
但这不起作用,因为facet_wrap中没有labeller函数。
but this didn't work because there is no "labeller" function in facet_wrap. How could this be done using grid?
推荐答案
这个例子应该让你开始:
This example should get you started:
library("ggplot2")
library("grid")
d <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() +
facet_wrap(~Species)
grob <- ggplotGrob(d)
strip_elem <- grid.ls(getGrob(grob, "strip.text.x", grep=TRUE, global=TRUE))$name
grob <- grid::editGrob(grob, strip_elem[1], label=expression(alpha[1]))
grob <- grid::editGrob(grob, strip_elem[2], label=expression(beta^2))
grob <- grid::editGrob(grob, strip_elem[3], label=expression(hat(gamma)))
grid.draw(grob)
更新:可与 ggplot2
版本0.9.3一起使用(尽管使用 grid
修改 ggplot2
gr的方法aphics)
Update: this works with ggplot2
version 0.9.3 (although using grid
is a fragile way to modify ggplot2
graphics)
grob[["grobs"]][["strip_t.1"]][["children"]][[2]][["label"]] <- expression(alpha[1])
grob[["grobs"]][["strip_t.2"]][["children"]][[2]][["label"]] <- expression(beta^2)
grob[["grobs"]][["strip_t.3"]][["children"]][[2]][["label"]] <- expression(hat(gamma))
grid.draw(grob)
这篇关于如何使用网格编辑ggplot2对象以将数学表达式添加到facet标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!