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

ggplot facet_wrap consistently spaced categorical x axis across all facets

When using scales="free_x" in facet_wrap the default seems to be that every subplot will take up the same amount of horizontal space and the x axes in each subplot will be scaled in order for this to happen. Is it possible to have the scale of the x axes be constant across the facets (with the width of each subplot different if necessary)?

For example, running the following code produces a plot where the variables on the x axis on the right are further apart than on the left (since there are 2 and 3 different values of x respectively). Is there a way to make it so the space between a,b,c and d,e is the same?

library(ggplot2)
df <- data.frame(x=c("a", "b", "c", "d", "e"),
                 y=1:5,
                 type=c(1, 1, 1, 2, 2))


p <- ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  facet_wrap(.~type, scales = "free_x")
print(p)

enter image description here

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

Thanks!

>Solution :

You are looking for facet_grid() with the argument space = "free":

ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  facet_grid(.~type, scales = "free_x", space = "free")

Output is:

enter image description here

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