1

If I have the following plot

library(ggplot2)
ggplot(mtcars, aes(x=mpg, y=wt, color=as.factor(cyl))) + 
  geom_point(size=3) +  
  facet_wrap(~cyl)

Created on 2023-08-30 with reprex v2.0.2

how can I set the limits of the x axis of each subplot individually?

I.e.

  • 4: from 0 to 40
  • 6: from 10 to 50
  • 8: from -5 to 20

Thank you very much! (Note: not sure if that question was already asked, but I could not find anything that shows this specific use case)

EDIT regarding marking as duplicate: The question that the duplicate remark refers to is one possible answer, however the accepted answer is a much nicer solution.

Revan
  • 2,072
  • 4
  • 26
  • 42
  • Is `facet_wrap(~cyl, scales = "free_x")` what you are looking for? i.e. are you happy for `ggplot` to set the axis limits on each facet as if they were individual plots, or do you specifically need to manually scale to the exact limits in your question? – SamR Aug 30 '23 at 08:31
  • I need to set the exact limits manually to show how large each group can get at maximum. – Revan Aug 30 '23 at 08:33
  • OK I think this is a duplicate of [this](https://stackoverflow.com/questions/42588238/setting-individual-y-axis-limits-with-facet-wrap-not-with-scales-free-y) question then. Have you tried that? I am not sure though because the values you give in the question are not the minimum and maximum for each group. – SamR Aug 30 '23 at 08:36
  • Yes, you are right. Thank you for the hint, that is one possibility. Ironically, I already had the variable in the dataset. – Revan Aug 30 '23 at 08:43

1 Answers1

2

I believe the package ggh4x could be helpful in this case, it allows you to set individual scale_x_continuous for each facet.

For example, your ggplot has three facets, you can supply a list (my custom_x for example) with three scale_x_continuous in ggh4x::facetted_pos_scales(). For this to work, you need to set facet_wrap(scales = "free_x").

library(ggplot2)
library(ggh4x)

custom_x <- list(
  scale_x_continuous(limits = c(0, 40)),
  scale_x_continuous(limits = c(10, 50)),
  scale_x_continuous(limits = c(-5, 20))
)

ggplot(mtcars, aes(x=mpg, y=wt, color=as.factor(cyl))) + 
  geom_point(size=3) +  
  facet_wrap(~cyl, scales = "free_x") +
  facetted_pos_scales(x = custom_x)

Created on 2023-08-30 with reprex v2.0.2

benson23
  • 16,369
  • 9
  • 19
  • 38