How does ggplot scale_continuous expand argument work?

Viewed 32889

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.

2 Answers

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

Related