Search code examples
rggplot2facet

Use different scale tick mark labelling functions with facet_wrap() in ggplot2


My question is similar to this question but differs in an important aspect. I want to use different labelling functions created with the {scales} package for the tick mark labels (not the axis labels). Here's a reproducible example:

library(ggplot2)
library(scales)

mill <- number_format(scale = 1/1000000, suffix = " M")
thou <- number_format(scale = 1/1000, suffix = " k")

df <- data.frame(cond = rep(c("A", "B", "C"), each = 5),
           x_unit = rep(1:5, 3),
           y_unit = round(c(rnorm(5, 5e6, 10000),
                      rnorm(5, 5e6, 10000),
                      rnorm(5, 5000, 1000))))

ggplot(df, aes(x = x_unit, y = y_unit)) +
  geom_line() +
  scale_y_continuous(labels = mill) +
  facet_wrap(~ cond, scales = "free_y")

Example Output

You might already see where I'm going with this: For facet C, I want to use the labelling function thou and not mill. How would I do that? I'm pretty sure that the solution with the labeller argument in facet_wrap() from the question I linked above does not apply here, right?


Solution

  • You might be interested in ggh4x::scale_y_facet(). You give it a way to find the appropriate panel cond == "C" and give it a different label function than the default scale. It only works with facets where scales are free. Disclaimer: I'm the author of ggh4x.

    library(ggplot2)
    library(scales)
    
    mill <- number_format(scale = 1/1000000, suffix = " M")
    thou <- number_format(scale = 1/1000, suffix = " k")
    
    df <- data.frame(cond = rep(c("A", "B", "C"), each = 5),
                     x_unit = rep(1:5, 3),
                     y_unit = round(c(rnorm(5, 5e6, 10000),
                                      rnorm(5, 5e6, 10000),
                                      rnorm(5, 5000, 1000))))
    
    ggplot(df, aes(x = x_unit, y = y_unit)) +
      geom_line() +
      scale_y_continuous(labels = mill) +
      facet_wrap(~ cond, scales = "free_y") +
      ggh4x::scale_y_facet(cond == "C", labels = thou)
    

    Created on 2022-11-24 by the reprex package (v2.0.1)