我们似乎没有担心过数据点被画到axes之外,这是因为ggplot2会在data range和axes之间加一些padding,以保证数据和坐标轴不会重叠:
来自scale_x_continous()的usage
expand
For position scales, a vector of range expansion constants used to add some padding around the data to ensure that they are placed some distance away from the axes. Use the convenience function expansion() to generate the values for the expand argument. The defaults are to expand the scale by 5% on each side for continuous variables, and by 0.6 units on each side for discrete variables.
expansion()
用来生成scale expansion vectors作为expand
参数的值。expansion()
接受两个参数mult
和add
分别对应生成乘性因子和加性因子。
加性参数和乘性参数的区别是:加性参数基于data variable扩展,乘性参数基于axis range进行扩展。
expansion(mult = 0, add = 0)
输入参数:向量,若长度为1,如mult=0.1则range的上下均扩展10%;
若长度为2,如mult=(0.1,0.2),则向下扩展10%,向上扩展20%。
> expansion(mult = c(0.1,0.2), add = c(3,4))
[1] 0.1 3.0 0.2 4.0
# 第一个值:乘性下限;第二个值:加性下限;第三个值:乘性上限;第四个值:加性上限
对scale函数中的expand
参数,需要是一个长度为2或4的向量。当长度为2,例如expand=c(0.1,0.2)
,表示分别向上下扩展10%,向上下加0.2,等价于expand=c(0.1,0.2,0.1,0.2)
,等价于expand=expansion(mult=c(0.1,0.1),add=c(0.2,0.2))
,即expansion(mult=0.1,add=0.2)
。