Search code examples
rggplot2labelfacet

R facet labels with expressions using label_parsed


I'm trying to put expressions into facet labels using label_parsed but with no success:

library(ggplot2)
mpg3 <- mpg
levels(mpg3$drv)[levels(mpg3$drv)=="4"] <- "4^{wd}"
levels(mpg3$drv)[levels(mpg3$drv)=="f"] <- "- Front %.% e^{pi * i}"
levels(mpg3$drv)[levels(mpg3$drv)=="r"] <- "4^{wd} - Front"


ggplot(mpg3, aes(x=displ, y=hwy)) + geom_point() +
  facet_grid(. ~ drv, labeller = label_parsed)

The plot that I get lacks expressions - facet labels contain the original levels of drv variable.

If I type levels(mpg3$drv) I get character(0).


Solution

  • There are two problems - firstly mpg$drv is character, not factor, and secondly, you need to set the factor labels, not the levels. I think this is what you want...

    mpg3 <- mpg
    mpg3$drv <- factor(mpg3$drv,
                       levels=c("4","f","r"),
                       labels=c("4^{wd}","- Front %.% e^{pi * i}","4^{wd} - Front"))
    
    ggplot(mpg3, aes(x=displ, y=hwy)) + 
          geom_point() +
          facet_grid(. ~ drv, labeller = label_parsed)
    

    enter image description here