Asymmetric expansion of ggplot axis limits

I have now tried to add code for this to ggplot2; see issue #1669 and the corresponding pull request. If it is accepted, the syntax for the expand argument will been changed from c(m, a) to c(m_lower, a_lower, m_uppper, a_upper), for specifying separate expansion values for the lower and upper range limits. (The old syntax will still continue to work, though, as the first two elements will be reused if elements three and/or four are missing.)

With this new syntax, you can use

ggplot(mtcars) +
  geom_bar(aes(x = cyl), width = 1) +
  scale_y_continuous(expand = c(0, 0, 0.05, 0))

The result looks like this:

Simple bar chart

It also works with facetting:

ggplot(mtcars) +
  geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
  facet_grid(vs ~ ., scales = "free_y") +
  scale_y_continuous(expand = c(0, 0, 0.05, 0))

Bar chart with facetting


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))) 

enter image description here

Tags:

R

Ggplot2