Home > database >  How to increase the default y-axis limit in ggplot when scales in facet_wrap() are set to "free
How to increase the default y-axis limit in ggplot when scales in facet_wrap() are set to "free

Time:07-21

I am trying to figure out how to change the global default setting of the y-axis limit in ggplot when facet_wrap() is used and scales are "free". I have searched the site but couldn't find any solution to my problem. I know I could build each plot separately and then assemble them using cowplot::plot_grid() or something similar but this will be cumbersome with 10 subplots.

Example data and plot:

library(tidyverse)
d <- tibble(
  var = c(rep(LETTERS[1:2], each = 4)),
  id = c(rep(1:4, 2)),
  mean = c(23, 24, 21, 22, 154, 153, 152, 151),
  sd = c(rep(c(2, 10), each = 4)),
  diff = c(rep(letters[1:4], 2))
)

ggplot(d, aes(id, mean))  
  geom_point()  
  geom_errorbar(aes(ymin = mean - sd,
                    ymax = mean   sd))  
  geom_text(aes(
    x = id,
    y = mean   sd,
    vjust = -2,
    label = diff
  ))  
  facet_wrap( ~ var, scales = "free_y")

Resulting graph: enter image description here

The problem I am encountering is that the letters are out of range when using the vjust = -2 argument. I am aware that in this example I can simply change the vjust argument but in my actual dataset this won't resolve the issue unfortunately. So my question is, assuming vjust = -2 is fixed, is there a way to increase the default y-axis limits when scales = "free" in facet_wrap().

CodePudding user response:

An option is to expand the axis limits.

ggplot(d, aes(id, mean))  
    geom_point()  
    geom_errorbar(aes(ymin = mean - sd,
                      ymax = mean   sd))  
    geom_text(aes(
        x = id,
        y = mean   sd,
        vjust = -2,
        label = diff
    ))  
    facet_wrap( ~ var, scales = "free_y")   
    scale_y_continuous(expand = expansion(mult = c(0.1, 0.2)))

enter image description here

This increases the top range by 20% and the bottom by 10%. AFAIK, the defaults are mult = c(0.05, 0).

  • Related