Search code examples
rggplot2expressionfacet-wrap

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


I have a data frame with single continuous variable (x) and a categorical variable (id). Data are generated as:

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

A plot I'm considering is generated using the following lines of code:

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

where a facet_names object is defined as a mapping vector:

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"
)

I wonder how to format the labels in a facet_wrap call as i1, i2, ..., i8, BLA

However, in the current settings, the labels are plotted as 1, 2, ..., BLA (i.e., without letter "i" and a number in a subscript).

Thanks for any pointer.


Solution

  • One approach is to convert id to a factor with levels specified in facet_names and then use label_parsed as the labeller function, interpreting the labels as plotmath expressions:

    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)