2

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)

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

fancy_labs <- as_labeller(~recode(., !!!c('2seater' = 'Seats Two!', 'compact' = "Small Family Car"))) should work too if I am not mistaten, though recode is superseded (think so)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.