Search code examples
rggplot2facetfacet-wrap

Custom y axis breaks of facet_wrap


I have created a faceted plot with facet_wrap, and I would like to change the breaks of y axis of all facets.

This is my current plot:

ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl) )) +
  geom_point(size=3) +
  facet_wrap(~cyl,scales = "free_y") +
  theme(legend.position="none")

enter image description here

This is my desired y axis breaks:

p = ggplot(data=mtcars, aes(x=mpg, y=wt)) +
  geom_point(size=3) +
  theme_classic()
ymax <- ceiling(max(mtcars$wt))
p + scale_y_continuous(breaks = c(0, ymax), expand = c(0, 0)) + expand_limits(y = ymax)

enter image description here


Solution

  • If you have a 'rule' for the y-axis breaks/limits you can provide a function to these arguments of the scale, which will evaluate that function for every facet. Note that the limits function gets the 'natural' data limits as argument, whereas the breaks function gets the expanded limits as argument.

    library(ggplot2)
    
    p <- ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl) )) +
      geom_point(size=3) +
      facet_wrap(~cyl,scales = "free_y") +
      theme(legend.position="none")
    
    p + scale_y_continuous(
      limits = ~ c(min(.x), ceiling(max(.x))),
      breaks = ~ .x[2],
      expand = c(0, 0)
    )
    

    Alternatively, if you need to tweak the y-axis of every panel, you might find ggh4x::facetted_pos_scales() useful. Disclaimer: I'm the author of ggh4x.

    p + ggh4x::facetted_pos_scales(y = list(
      cyl == 4 ~ scale_y_continuous(limits = c(0, NA)),
      cyl == 6 ~ scale_y_continuous(breaks = c(2.9, 3, 3.1)),
      cyl == 8 ~ scale_y_continuous(trans = "reverse")
    ))
    

    Created on 2022-07-16 by the reprex package (v2.0.1)