Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use custom scales for each facet

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading