Search code examples
rggplot2labelfacet-grid

R: Subscript on one facet axis, multiple lines on the other


I made a plot in R with ggplot2 with 4 variables, 2 of which I put into facets. One axis has labels with subscript, and on the other axis I want one of my labels to be on 2 lines. I found a similar topic here: parsed labels along one facet axis, unparsed labels along the other, but this doesn't solve my problem. The subscript works, but I only see 1 line instead of 2 for the other variable. I used ggplot2's mpg data to create an example.

This is my code:

#LOAD PACKAGES

library(ggplot2)
library(tidyverse)


#reduce dataset for convenience reasons
mpg <- filter(mpg, manufacturer == "audi" | manufacturer == "chevrolet") %>%
  select(manufacturer, year,cty,hwy)

#create factor for manufacturer and rename
mpg$manufacturer_f <- factor(mpg$manufacturer, levels = c("audi", "chevrolet"), labels = c(
  "audi[subscript]", 
  "chevrolet"))

#create factor for year and rename
mpg$year_f <- factor(mpg$year, levels = c("1999", "2008"), labels = c(
  "1999", "2008\nlongline"))

#Labeller function
L <- function(labels,multi_line=TRUE) {
  r <- if (all(grepl("\n",labels[[1]]))) {
    list(as.character(labels[[1]]))
  } else {
    label_parsed(labels,multi_line=multi_line)
  }
  ## browser()
  return(r)
}
class(L) <- "labeller"


testplot <- ggplot(mpg, aes(x=cty, y= hwy)) +
  geom_line()+
  facet_grid(manufacturer_f ~ year_f, scales = "free_x", space = "free", labeller = L)

What it going wrong? I looked at this topic too: ggplot2: Splitting facet/strip text into two lines and this worked for another graph with only 1 facet but not in this case. I use RStudio 2022.12.0 and R version 4.2.2.

My plot looks like this but the 2008 label should have 2 lines here: https://i.sstatic.net/5OMzo.png


Solution

  • At least for your example data and code using any in your labeller function instead of all would fix the issue:

    library(ggplot2)
    
    L <- function(labels, multi_line = TRUE) {
      r <- if (any(grepl("\n", labels[[1]]))) {
        list(as.character(labels[[1]]))
      } else {
        label_parsed(labels, multi_line = multi_line)
      }
      return(r)
    }
    class(L) <- "labeller"
    
    ggplot(mpg, aes(x = cty, y = hwy)) +
      geom_line() +
      facet_grid(manufacturer_f ~ year_f, scales = "free_x", space = "free", labeller = L)
    

    enter image description here