0

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'm new here so I hope this is enough yet not too much info. 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 2021.09.2 and R version 4.1.2.

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

Mandy
  • 1
  • 1
  • Welcome, can you please share your data using `dput()` or smiliar? You are more likely to get an answer if others are able to run your code. See [this question](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for examples of how to include data in R questions. – Jan Boyer Mar 07 '22 at 16:34

0 Answers0