I am trying to figure out how scale_continuous()
expand
argument works. According to scale_continuous documentation:
A numeric vector of length two giving multiplicative and additive expansion constants. These constants ensure that the data is placed some distance away from the axes. The defaults are c(0.05, 0) for continuous variables, and c(0, 0.6) for discrete variables.
Since they are "expansion constants", they are not actual units. Is there any way to convert them to some actual measurement to predict the actual output? For anything except 0, I just try random numbers until it works. There must be a more proper way to approach this.
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
.