Custom y axis breaks of facet_wrap
Asked Answered
B

2

4

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

Bismuthic answered 13/7, 2022 at 7:5 Comment(6)
The desired example doesn't seem to be related to mtcars. What is df$len?Narghile
Sorry, I have corrected this.Bismuthic
What is then wrong? p + scale_y_continuous(breaks = c(0, ymax), expand = c(0, 0)) + expand_limits(y = ymax) produces a 0-6 y-scale.Narghile
I want to create different y axis breaks to different facet, eg: 0-4 in facet 4, 0-4 in facet 6 and 0-6 in facet 8.Bismuthic
perhaps have a look at https://mcmap.net/q/495836/-ggplot2-change-axis-limits-for-each-individual-facet-panelNarghile
Nice, I will hava a try!Bismuthic
V
13

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)

Vladi answered 16/7, 2022 at 19:8 Comment(0)
O
-1

Sorry, you haven't give any information about 'df'. so I can't run the code in the 2rd section.(ymax <- ceiling(max(df$len)))

In general, to change the breaks of y axis, you could use scale_y_continuous(breaks = c(), labels = c(), limits = (), ...). And use facet_wrap(~var) to plot facet.

Please supply more information about 'df'.

Oler answered 13/7, 2022 at 7:33 Comment(1)
Yes, the question is how to apply different y axis breaks to different facet?Bismuthic

© 2022 - 2025 — McMap. All rights reserved.