Search code examples
rggplot2facet-wrap

How to set equal panel horizontal space when use scale = "free_y"?


set.seed(3)

data <- tibble(Group = c(rep("g1", 10), rep("g2", 10), rep("g3", 10)), 
    Value = c(runif(10, min = 1, max=5), runif(10, min = 1, max=5), runif(10, min = -5, max=5)))

ggplot(data, aes(Group, Value)) + 
    geom_point() + 
    facet_wrap(~ Group, scales = "free")

You can see when y with decimal/negative values, the space become bigger.

enter image description here


Solution

  • You can set a fixed width for your y-axis labels

    ggplot(data, aes(Group, Value)) + 
      geom_point() + 
      facet_wrap(~ Group, scales = "free") +
      scale_y_continuous(labels = function(label) sprintf("%10.1f", label))
    

    Or flip the plot with coor_flip()

    ggplot(data, aes(Group, Value)) + 
      geom_point() + 
      facet_wrap(Group ~ ., scales = "free") +
      coord_flip()
    

    Created on 2019-04-10 by the reprex package (v0.2.1.9000)