R:ggplot2:facet_grid:如何在少数(不是全部)标签中包含数学表达式?

R : ggplot2 : facet_grid : how include math expressions in few (not all) labels?

我在 ggplot2 上遇到了一些问题。我阅读了大部分相关帖子,尝试了一些东西但没有找到任何真正的解决方案。

我想在 facet_gridsggplot2 的标签中包含数学表达式。

结果:

Label of facet 1 is written on the graph : control

Label of facet 2 is written on the graph : "100 µg ".L^"-1""" …

我不想那样。

我不想使用 facet_grid(.~group, labeller=label_bquote(…)) 因为我不想我所有的标签都遵循相同的表达式。我想一个一个编辑标签手动… 我尝试使用 bquote(…) 而不是 expression(…) 但同样的错误结果发生了

有人对此有任何线索吗?


一个例子:我定义了一个数据框:

activity<- as.numeric(c("44","41","48","43","42","45","44","39", "47", "68", "88", "57"))
group<-c("first","first","first","first","first","first",
         "second","second","second","second","second","second")
day<- c("0", "0", "0", "20","20", "20","0", "0", "0", "20","20", "20" )
a<-data.frame(activity, group, day)

我作图:

require (ggplot2) 

qplot(day, activity, facets=.~group, data=a, ylim=c(25,90))

我想更改小平面标签和 y 轴的名称:

levels(a$group)<- c("control", expression("100 µg "*.L^"-1"*""))
qplot(day, activity, facets=.~group, data=a, ylim=c(25,90),
  ylab=expression("fmol "*.µl^"-1"*""))

它适用于 y-axis,但是对于 facet 标签,它不起作用... 有什么线索吗?

建议的解决方案:

先决条件:

activity <- as.numeric(c("44", "41", "48", "43", "42", "45", 
  "44", "39", "47", "68", "88", "57"))
group <- c("first", "first", "first", "first", "first", "first", 
  "second", "second", "second", "second", "second", "second")
day <- c("0", "0", "0", "20", "20", "20", "0", "0", "0", "20", 
  "20", "20")
a <- data.frame(activity, group, day)
require(ggplot2)
levels(a$group) <- c("control", expression("100 µg " * .L^"-1" * ""))

建议的解决方案:

p1 <- qplot(day, activity, data = a)
p1 + facet_grid(. ~ group, labeller = label_parsed)

结果:

说明

我们将标签结构创建为一个字符串,我们在其中创建一个公式,注意使用 ~ 替换空格...然后我们告诉 facet_grid() 解析传递给它的标签字符串通过设置 labeller = label_parsed...

作为公式

注意:?plotmath中描述了显示的细节,但请注意geom_text()facet_grid()使用字符串,而不是表达式。

希望以上内容对您有所帮助。

参考:

查看 Hagley Wickham 关于贴标机的页面...:https://github.com/hadley/ggplot2/wiki/labeller

您可以使用 label_parsed,前提是您的所有标签都是有效的表达式(如有必要,您可以将文本放在引号内)

library(ggplot2) 
levels(a$group)<- c("'control test'", "100~mu*g*'.L'^-1")
ggplot(a) + facet_grid(.~group, labeller=label_parsed)