Search code examples
rggplot2legendfacetfacet-grid

How to add greek letters to Facet_Grid strip labels?


I have created the plot below using facet_grid and have used the labeller argument to add "p=" and "mu[2]" labels to the gray strips around the grid. I would like to replace "mu[2]" labels, which I have indicated with red rectangles, with the greek letter mu with subscript 2. I would appreciate if someone could help me with that. If needed, I can upload the data and my code.

enter image description here


Solution

  • If you encode your facetting variables as character plotmath expressions you can use label_parsed() as labeller argument to the facet. Example below:

    library(ggplot2)
    
    df <- expand.grid(1:3, 1:3)
    df$FacetX <- c("'p = 0.1'", "'p = 0.5'", "'p = 0.9'")[df$Var1]
    df$FacetY <- c('mu[2]*" = 0.1"', 'mu[2]*" = 1"', 'mu[2]*" = 10"')[df$Var2]
    
    ggplot(df, aes(Var1, Var2)) +
      geom_point() +
      facet_grid(FacetY ~ FacetX, labeller = label_parsed)
    

    Created on 2020-08-26 by the reprex package (v0.3.0)

    EDIT:

    Based on your comment that the variables are encoded as numerics, I think the glue package might help you construct these labels.

    library(ggplot2)
    library(glue)
    
    df <- expand.grid(1:3, 1:3)
    df$FacetX <- c(0.1, 0.5, 0.9)[df$Var1]
    df$FacetY <- c(0.1, 1, 10)[df$Var2]
    
    ggplot(df, aes(Var1, Var2)) +
      geom_point() +
      facet_grid(glue('mu[2]*" = {FacetY}"') ~ glue("'p = {FacetX}'"), 
                 labeller = label_parsed)
    

    Created on 2020-08-26 by the reprex package (v0.3.0)