Search code examples
rggplot2labelfacet-wrap

Using a labelling function to rename some but not all variables in ggplot2


When using a labeller function in ggplot2, is it possible to apply it only when the original value is found in the lookup table? In the example below, I'm using as_labeller() to rename some of the car classes. Anything that isn't in the lookup table defaults to "NA". I'd like it to keep its original name. Is this possible?

library(ggplot2)

#base plot without any labels
p <- ggplot(mpg, aes(displ, hwy)) + geom_point()
p + facet_wrap(~class)

#add fancy labels - but only for some classes
fancy_labs <- as_labeller(c('2seater' = 'Seats Two!', 'compact' = "Small Family Car"))
p + facet_wrap(~class, labeller = fancy_labs)

enter image description here enter image description here

I'd like the headers of the second plot to read: "Seats Two!" "Small Family Car" "midsize" "minivan" (etc)


Solution

  • As far as I can tell I don't see an easy to specify the default value if things don't match with as_labeller, but you can also wrap a function as a labeller and could use dplyr::case_match as a helper. For example

    fancy_labs <- as_labeller(\(x) dplyr::case_match(x, 
      '2seater' ~ 'Seats Two!',
      'compact' ~ "Small Family Car",
      .default=x)
    )
    p + facet_wrap(~class, labeller = fancy_labs)
    

    enter image description here