Search code examples
rggplot2dplyrplotmath

R plotmath expression to show range of values in ggplot


I am struggling to get expression to communicate something like 10<=VarName<120. Why does the following code fail?

starwars %>% 
  filter(between(birth_year, 10, 120)) %>% 
  ggplot(aes(x=mass, y=height)) +
  geom_point() +
  labs(title=expression(10<="Birth Year"120))

Notice that this alone works (without the 120 on the end):

starwars %>% 
  filter(between(birth_year, 10, 120)) %>% 
  ggplot(aes(x=mass, y=height)) +
  geom_point() +
  labs(title=expression(10<="Birth Year"))

Solution

  • A possible solution is:

    starwars %>% 
      filter(between(birth_year, 10, 120)) %>% 
      ggplot(aes(x=mass, y=height)) +
      geom_point() +
      labs(title=expression(paste(10<="Birth Year<",120, sep = "")))
    

    Another solution (more complex, but better)

    starwars %>% 
      filter(between(birth_year, 10, 120)) %>% 
      ggplot(aes(x=mass, y=height)) +
      geom_point() +
      labs(title = parse(text = paste0('"10" <= ', ' ~ "Brith Year" <= ', '~ 120')))