rggplot2facetfacet-wrap

How to use labeller with facet wrap to generate unique facet labels?


Consider this example if I wanted each facet to be labelled with the first 11 letters of the alphabet? rather than the value of gear then carb.

data(mtcars)
ggplot(mtcars)+
  geom_point(aes(x = hp, y = disp))+
  facet_wrap(gear~carb, labeller = c(LETTERS[1:11]))

I can't use facet_grid


Solution

  • This can be achieved like so:

    labels is a data.frame with two cols gear and carb where each row corresponds to one combination of the two vars. The labeller should return a list or dataframe, e.g. when using a list the first element if the first line of the label, the second element the second line ...

    Hence to label the facets with letters we just have to return a list with one element, i.e. the first nrow(labels) elements of LETTERS.

    library(ggplot2)
    
    ggplot(mtcars) +
      geom_point(aes(x = hp, y = disp)) +
      facet_wrap(
        gear ~ carb,
        labeller = function(labels) list(LETTERS[seq_len(nrow(labels))])
      )