Home > Back-end >  Cannot add superscripts to facet label in ggplot
Cannot add superscripts to facet label in ggplot

Time:02-02

I cannot make the facet wrap for Rsquared have a 2 superscript. I know there are many questions about this but I have tried the suggestions and cannot make it work. Here is what I have:

my_labeller <- as_labeller(c( MAE = "MAE", RMSE = "RMSE", R2= "*R^2*",
                       default = label_parsed))

And then:

error %>% mutate(across(Metric, factor, levels=c("MAE" , "RMSE" , "R2"), labels = 
c("MAE" , "RMSE" , "R^2"))) %>%
ggplot(aes(x=Buffer, y=Value, group=Model)) 
geom_line(aes(color=Model))  
geom_point(aes(color=Model))  
theme_bw()  
labs(y = "Value", x = bquote('Buffer radius (m)'))  
facet_wrap(~ Metric, nrow = 3, scales = "free_y", labeller=my_labeller)

But the graph still has R^2

enter image description here

CodePudding user response:

Your code looks nearly correct to me, but the "*" characters are unnecessary. In fact when I try to use "*", R throws an error.

Your use of factor to change the label names is also unnecessary, and will cause the labeler to miss the label for "R2" entirely, since you have re-labeled it "R^2".

Syntax for setting mathematical expressions in facet labels has changed between versions of ggplot, so a lot of the advice out there is out of date. The following works with ggplot 3.3.5. Construct a labeller using as_labeller and specify default = label_parsed.

In this example, I am modifying the "cyl" column of the "mtcars" data set to closely match your situation (the mutate line). Note that the names of the labeller vector must match the labels you define in factor. The values of the labeller can be anything.

library(tidyverse)

my_labeller = as_labeller(
  c(
    MAE = 'MAE', 
    RMSE = 'RMSE', 
    `R^2` = 'R^2'
    ), 
  default = label_parsed
)

mtcars %>% 
  mutate(cyl = factor(cyl, levels = c(4, 6, 8), labels = c('MAE', 'RMSE', 'R^2'))) %>% 
  ggplot(data = ., aes(x = carb, y = mpg))  
  geom_point()  
  facet_grid(~cyl, labeller = my_labeller)

enter image description here

  •  Tags:  
  • Related