Skip to content

Facet_wrap and scale="free" unexpectedly centers y-axis at zero in ggplot2 #3849

@trichterhb

Description

@trichterhb

From this dataframe


     df <- data.frame(cat=c(rep("X", 20),rep("Y", 20), rep("Z",20)), 
                         value=c(runif(20),runif(20)*100, rep(0, 20)), 
                         var=rep(LETTERS[1:5],12))

i want to create facetted boxplots. One facet would contain only Zeros.

library(ggplot2)
  

  p1 <- ggplot(df, aes(var,value)) + geom_boxplot() + facet_wrap(~cat, scale="free") 
  p1

The results is aesthetically dissactisfactory as it centers the y-axis of the empty panel at zero. Note, that "scale="free"" causes this. I want to start all y-scales at zero. I tried several solutions found on the web:

    p1 + scale_y_continuous(expand = c(0, 0)) # not working
    p1 + expand_limits(y = 0) #not working
    p1 + scale_y_continuous(limits=c(0,NA)) ## not working
    p1 + scale_y_continuous(limits=c(0,100)) ## partially working, but defeats scale="free"
    p1 + scale_y_continuous(limits=c(0,max(df$value))) ## partially working, see above
    p1 + scale_y_continuous(limits=c(0,max(df$value))) + expand_limits(y = 0)## partially working, see above

One solution would possibly be to replace the zero's with very tiny values, but maybe you can find a more straightforward solution. Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions