facet_wrap() 在 ggplot 中结合了数学表达式和字符串

facet_wrap() in ggplot with a combination of math expressions and a string

我有一个包含单个连续变量 (x) 和一个分类变量 (id) 的数据框。数据生成为:

library(tidyverse)
df <- tibble(id = rep(1:9, each = 50), x = rnorm(450)) %>%
    mutate(id = replace(id, id == 9, "BLA"))

我正在考虑的情节是使用以下代码行生成的:

ggplot(df, aes(x = x)) +
    geom_histogram() +
    facet_wrap(~ id, labeller = labeller(id = facet_names))

其中 facet_names 对象定义为映射向量:

facet_names <- c(
    `1` = expression(i[1]),
    `2` = expression(i[2]),
    `3` = expression(i[3]),
    `4` = expression(i[4]),
    `5` = expression(i[5]),
    `6` = expression(i[6]),
    `7` = expression(i[7]),
    `8` = expression(i[8]),
    `9` = "BLA"
)

我想知道如何将 facet_wrap 调用中的标签格式化为 i1, i2, ... , i8, BLA

但是,在当前设置中,标签绘制为 1、2、...、BLA(即没有字母 "i" 和下标中的数字)。

感谢您的指点。

一种方法是将 id 转换为具有 facet_names 中指定水平的因子,然后使用 label_parsed 作为标签函数,将标签解释为 plotmath 表达式:

library(dplyr)
library(ggplot2)

df <- mutate_at(df, .vars = "id", .funs = factor, labels = facet_names)

ggplot(df, aes(x = x)) +
    geom_histogram() +
    facet_wrap(~ id, labeller = label_parsed)