How does ggplot scale_continuous expand argument work?

The document is pretty clear. If you set limits manually, it would be more clear. I'll give some examples to show how it works:

the first argument gives expansion equal to its multiplication by limit range;

ggplot(mpg, aes(displ, hwy)) +
    geom_point() +
    scale_x_continuous(limits = c(1, 7), expand = c(0.5, 0))
# right most position will be 7 + (7-1) * 0.5 = 10

the second gives the absolute expansion added to both end of the axis:

ggplot(mpg, aes(displ, hwy)) +
    geom_point() +
    scale_x_continuous(limits = c(1, 7), expand = c(0.5, 2))
# right most position will be 7 + (7-1) * 0.5  + 2 = 12

Finally, the same expansion applies to both end of the axis.


2019-01-23: I learned from @C.Liu answer that the new expand_scale function could be used to achieve different expansion of lower limits and upper limits. The multi and add parameters are similar to the two values required for expand = but allows a vector of length two for setting the lower limit and upper limit. See C.liu's answer for detail.

2020-11-25: expand_scale() is deprecated at least since version 3.3.2, use expansion() instead. This is a name change only. The name and meaning of parameters of expansion remain the same as expand_scale.


expand_scale could be the choice for fine tuning only one end of the axis.

ggplot(mpg, aes(displ, hwy)) +
geom_point() +
scale_x_continuous(limits = c(1, 7), 
                   expand = expand_scale(mult = c(0, 0.5), 
                                         add = c(2, 0))
# left most position will be 1 - (7-1) * 0.0  -2 = -1, 
# right most position will be 7 + (7-1) * 0.5 = 10

This is a convenience function for generating scale expansion vectors for the expand argument of scale__continuous and scale__discrete. The expansions vectors are used to add some space between the data and the axes.

expand_scale(mult = 0, add = 0)

Arguments mult

vector of multiplicative range expansion factors. If length 1, both the lower and upper limits of the scale are expanded outwards by mult. If length 2, the lower limit is expanded by mult1 and the upper limit by mult[2]. add

vector of additive range expansion constants. If length 1, both the lower and upper limits of the scale are expanded outwards by add units. If length 2, the lower limit is expanded by add1 and the upper limit by add[2].

Generate expansion vector for scales