rggplot2

facet_wrap parse error when using greater than or equal to symbol


I am trying to change the title of two plots made using facet_wrap(), one of which has a greater than or equal to symbol (>=). I can get the plots to parse the title, but as soon as I put the >= symbol in parenthesis, the titles fail to parse. How can I get the titles to parse when the >= symbol is in parenthesis?

library(tidyverse)

mtcars %>% 
  mutate(size = ifelse(hp >= 100, 'greater', 'lesser'),
         size = factor(size, levels = c("greater", "lesser"),
                       labels = c("Horsepower >= 100", "Horsepower < 100"))) %>% 
  ggplot(aes(x = mpg, y = wt)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~size, labeller = label_parsed)

Fails to parse when putting >= in parenthesis.


mtcars %>% 
  mutate(size = ifelse(hp >= 100, 'greater', 'lesser'),
         size = factor(size, levels = c("greater", "lesser"),
                       labels = c("Horsepower (>= 100)", "Horsepower (< 100)"))) %>% 
  ggplot(aes(x = mpg, y = wt)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~size, labeller = label_parsed)
#> Error in parse(text = as.character(values)): <text>:1:13: unexpected '>='
#> 1: Horsepower (>=
#>                 ^

Created on 2024-11-18 with reprex v2.1.1


Solution

  • 1) Ensure that the labels are valid R:

    mtcars %>% 
      mutate(size = ifelse(hp >= 100, 'greater', 'lesser'),
             size = factor(size, levels = c("greater", "lesser"),
                           labels = c("Horsepower ~ '('>= 100*')'", 
                                      "'Horsepower (< 100)'"))) %>% 
      ggplot(aes(x = mpg, y = wt)) +
      geom_point() +
      theme_bw() +
      facet_wrap(~size, labeller = label_parsed)
    

    screenshot

    2) Another approach is to use unicode 2265 for >=. In that case omit labeller=...

    mtcars %>% 
      mutate(size = ifelse(hp >= 100, 'greater', 'lesser'),
             size = factor(size, levels = c("greater", "lesser"),
                           labels = c("Horsepower (\u2265 100)", 
                                      "Horsepower (< 100)"))) %>% 
      ggplot(aes(x = mpg, y = wt)) +
      geom_point() +
      theme_bw() +
      facet_wrap(~size)
    

    screenshot