Benny Goldman
Benny Goldman

Reputation: 55

Label parsing with for facet plot titles in ggplot

I am trying to pass a character variable with some mathematical symbols to ggplot facet, so that the titles of the individual plots nicely display with the appropriate math symbols. Is there a nice way to get the below code to work?

library(tidyverse)

plot_data <- mpg %>% 
  mutate(fvar=case_when(
    drv=="f" ~ "X >=10", 
    drv=="4" ~ "0<X<=1", 
    drv=="r" ~ "1<X<10"
  ))

ggplot(plot_data, aes(x=displ, y=cty)) + 
  geom_point() + 
  facet_wrap(~ fvar, labeller=label_parsed)

Upvotes: 1

Views: 175

Answers (1)

stefan
stefan

Reputation: 124438

This could be achieved by using invisible grouping via {} (see ?plotmath).

Using {} we can turn expressions like 0 < X <= 1 into a "valid" R like expression {0 < X} <= 1 which can be evaluated by label_parsed:

library(tidyverse)

plot_data <- mpg %>% 
  mutate(fvar=case_when(
    drv=="f" ~ "X >=10", 
    drv=="4" ~ "{0<X}<=1", 
    drv=="r" ~ "{1<X}<10"
  ))

ggplot(plot_data, aes(x=displ, y=cty)) + 
  geom_point() + 
  facet_wrap(~ fvar, labeller = label_parsed)

Upvotes: 1

Related Questions