Search code examples
rggplot2facet-wrap

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

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