Asymmetric expansion of ggplot axis limits

前端 未结 3 476
情深已故
情深已故 2020-12-03 01:16

How do you adjust the expansion of limits asymmetrically in ggplot? For example,

library(ggplot2)

ggplot(mtcars) + 
  geom_bar(aes(x = cyl), width = 1)
         


        
3条回答
  •  青春惊慌失措
    2020-12-03 01:35

    ggplot2 v3.0.0 released in July 2018 has expand_scale() option (w/ mult argument) to achieve OP's goal.

    Edit: expand_scale() will be deprecated in the future release in favor of expansion(). See News for more information.

    library(ggplot2)
    
    ### ggplot <= 3.2.1
    ggplot(mtcars) + 
      geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) + 
      facet_grid(vs ~ ., scales = "free_y") + 
      scale_y_continuous(expand = expand_scale(mult = c(0, .2))) 
    
    ### ggplot >= 3.2.1.9000
    ggplot(mtcars) + 
      geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) + 
      facet_grid(vs ~ ., scales = "free_y") + 
      scale_y_continuous(expand = expansion(mult = c(0, .2))) 
    

提交回复
热议问题