如何使用labeller = label_parsed在一些ggplot facet标签中包含表达式?

时间:2017-09-27 09:27:51

标签: r parsing plot ggplot2 label

我试图在几个但不是所有的ggplot facet标签中包含表达式。此question之前已被问及并已解决,但我无法使其适用于我的特定情况。

我收到以下错误:

  

解析时出错(text = as.character(values)):: 1:8:   意外的符号1:封顶的巢              ^

请让我知道我的错误是什么,以及如何在facet标签中绘制平方根符号。

数据:

df <- structure(list(t0 = c(122.883911266139, 169.48220216013, 121.371211764444, 
                            170.60152096912, 122.001873322486, 151.578850452806, 120.458523959951, 
                            149.550874882101, 3411.77083333332, 8846.04166666666, 3329.0625, 
                            8866.04166666666, 5931.79935833674, 4554.92435833674, 5618.75, 
                            5387.63269167007), Treatment = structure(c(1L, 1L, 2L, 2L, 1L, 
                                                                       1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("A", 
                                                                                                                               "B"), class = "factor"), Trait = structure(c(2L, 2L, 2L, 2L, 
                                                                                                                                                                            2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Capped brood cells", 
                                                                                                                                                                                                                                        "Colony strength", "sqrt(\"Colony weight (g)\")"), class = "factor"), 
                     Timepoint = structure(c(1L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 1L, 
                                             2L, 1L, 2L, 3L, 4L, 3L, 4L), .Label = c("2013 Before", "2013 After", 
                                                                                     "2014 Before", "2014 After"), class = "factor")), .Names = c("t0", 
                                                                                                                                                  "Treatment", "Trait", "Timepoint"), row.names = c(NA, 16L), class = "data.frame")

代码:

df$Trait = as.factor(df$Trait)
levels(df$Trait) <- c("Capped brood cells", "Colony strength", expression(sqrt("Colony weight (g)")))

dodge <- position_dodge(width=0.9)
ggplot(df, aes(x = Timepoint, y = t0, fill = Treatment))+
    geom_bar(position = dodge, stat="identity", color = "black")+
    facet_grid(Trait~., scales = "free_y", labeller = label_parsed)

1 个答案:

答案 0 :(得分:1)

据我所知,您的代码存在两个问题。首先,当您解析标签时,您需要用〜字符替换空格(这也在您链接的SO问题中注明)。这就是导致你看到错误的原因;解析器无法处理第一个因子级别中“Capped”和“brood”之间的空白。其次,您要分配三个因子级别,而数据中只有两个。

将“代码”块的前两行更改为以下内容会生成正确的图形:

df$Trait = as.factor(as.character(df$Trait))
levels(df$Trait) <- c("Capped~brood~cells", expression(sqrt("Colony weight (g)")))