ggplot scale_continuous如何扩展参数?

bur*_*ger 13 r ggplot2 tidyverse

我试图弄清楚scale_continuous() expand论证是如何运作的.根据scale_continuous文档:

长度为2的数字向量给出乘法和加法扩展常数.这些常量确保数据放置在离轴一定距离的位置.连续变量的默认值为c(0.05,0),离散变量的默认值为c(0,0.6).

由于它们是"扩展常数",因此它们不是实际单位.有没有办法将它们转换为实际测量值以预测实际输出?除了0之外的任何东西,我只是尝试随机数,直到它工作.必须有更合适的方法来解决这个问题.

mt1*_*022 24

该文件非常清楚.如果limits手动设置,则会更清楚.我将举一些例子来说明它是如何工作的:

第一个参数给出的扩展等于其乘以极限范围;

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
Run Code Online (Sandbox Code Playgroud)

第二个给出了轴两端的绝对膨胀:

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
Run Code Online (Sandbox Code Playgroud)

最后,相同的扩展适用于轴的两端.


2019-01-23:我从@ C.Liu那里得知,新expand_scale功能可用于实现下限和上限的不同扩展.的multiadd参数是类似的.所需要的两个值expand =,但允许长度为2的向量用于设定下限和上限.有关详细信息,请参阅C.liu的答案.

  • @burger,据我所知,没有这样的选择.但是你可以通过手动设置`limits`来解决,如果需要,可以选择将`expand`设置为`c(0,0)`. (3认同)

小智 16

expand_scale可以选择仅微调轴的一端.

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
Run Code Online (Sandbox Code Playgroud)

这是一个便利函数,用于为scale_ _continuous和scale_ _discrete 的expand参数生成比例扩展矢量.扩展向量用于在数据和轴之间添加一些空间.

expand_scale(mult = 0,add = 0)

参数mult

乘法范围扩张因子的向量.如果长度为1,则刻度的下限和上限均由多个向外扩展.如果长度为2,则下限由mult 1扩展,上限由mult [2] 扩展.加

加性范围扩展常数的向量.如果长度为1,则刻度的下限和上限均通过添加单位向外扩展.如果长度为2,则下限通过加1扩展,上限加上[2].

为比例生成扩展矢量

  • `expand_scale()` 已弃用;使用“expansion()”代替。 (2认同)