How does the ggplot scale_continuous expand argument work?

I am trying to understand as an scale_continuous()argument expand scale_continuous(). As per the documentation for scale_continuous :

Numeric vector of length two, giving multiplicative and additive extension constants. These constants provide data at a certain distance from the axes. Default values: c (0.05, 0) for continuous variables and c (0, 0.6) for discrete variables.

Since they are “expansion constants,” they are not valid units. Is there a way to convert them into some actual dimension in order to predict the actual result? For anything other than 0, I just try random numbers until this works. There should be a more correct approach to this.

+5
source share
2 answers

The document is pretty straightforward. If you install limitsmanually, it will be more clear. I will give some examples to show how this works:

the first argument gives an extension equal to its multiplication by the 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 an absolute extension added to both ends 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 extension applies to both ends of the axis.


2019-01-23: from @ C.Liu's answer, I found out what expand_scalecan be used to achieve different extensions of the ends of two axes. See C.liu's Answer for details.

+12
source

The expand_scale parameter can only fine tune 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

scale__continuous scale__discrete. .

expand_scale (mult = 0, add = 0)

. 1, . 2, mult 1, - mult [2].

. 1, . 2, 1, [2].

+7

Source: https://habr.com/ru/post/1694086/


All Articles