使用stat_function以对数刻度绘制R

Tom*_*tal 3 r ggplot2

我在尝试进入stat_functionR's时遇到了严重的问题ggplot2。我从这个简单的例子开始:

ggplot(data.frame(x = c(1, 1e4)), aes(x)) + stat_function(fun = function(x) x)
Run Code Online (Sandbox Code Playgroud)

它按预期工作。不幸的是,当我同时为x和y轴添加对数刻度时:

ggplot(data.frame(x = 1:1e4), aes(x)) +
  scale_x_log10() + 
  scale_y_log10() +
  stat_function(fun = function(x) x)
Run Code Online (Sandbox Code Playgroud)

我得到以下结果,这完全违反了身份功能。 在此处输入图片说明

我缺少一些非常基本的东西吗?那么,在对数刻度上绘制函数的正确且最少的技巧是什么?

编辑: 受到我继续回答并尝试使用比例和aesthetics参数的答案的启发。我更困惑地发现使用以下代码可以达到我的期望:

ggplot(data.frame(x = 1:1e4, y = 1:1e4), aes(x, y)) +
  scale_x_log10() + 
  scale_y_log10() +
  stat_function(fun = function(x) x)
Run Code Online (Sandbox Code Playgroud)

具有明显未使用的y值向量(即未使用stat_function)。轴转换是否取决于数据的可用性?

Did*_*rts 5

使用时,scale_x_log10()将对x值进行对数转换,然后才使用进行y值的计算stat_function()。然后将x值反向转换为原始值以进行缩放。y值保持为从对数转换后计算得出的值x。您可以通过绘制不带的值来检查scale_y_log10()。在情节中有一条直线。

ggplot(data.frame(x=1:1e4), aes(x)) +
    stat_function(fun = function(x) x) +
    scale_x_log10() 
Run Code Online (Sandbox Code Playgroud)

如果应用scale_y_log10(),则对已经计算的y值进行对数转换,因此将绘制曲线。


小智 5

在ggplot2中,规则是比例变换先于统计变换,再依次是坐标变换。在这种情况下,函数(通过stat_function())是统计转换。

如果在ggplot2调用中使用scale_x / y _ *()函数,则它将在计算该函数之前首先应用缩放转换。

情况0:以x和y的原始比例绘制。

ggplot(data.frame(x = 1:1e4, y = 1:1e4), aes(x, y)) +
    stat_function(fun = function(x) x)
Run Code Online (Sandbox Code Playgroud)

情况1a:由于存在scale_x / y_log10(),因此在计算函数之前x和y都进行了对数转换。您可以从它们各自标度上的值(与案例0比较)中看到这一点。

ggplot(data.frame(x = 1:1e4, y = 1:1e4), aes(x, y)) +
    stat_function(fun = function(x) x) +
    scale_x_log10() +
    scale_y_log10()
Run Code Online (Sandbox Code Playgroud)

情况1b:x在原始数据帧中被对数转换。因此,该函数实际上对log10(x)值进行运算,因此仍将是一条直线,但在x和y上都在log10刻度上。

ggplot(data.frame(x = log10(seq(1e4)), y = seq(1e4)), aes(x, y)) +
    stat_function(fun = function(x) x)
Run Code Online (Sandbox Code Playgroud)

情况1c:与1b相同,但有一个例外:x比例尺以原始单位表示,而y比例尺以log10(x)单位表示,因为x的比例尺转换发生在统计转换f(y)=计算y,其中y = log10(x)。

ggplot(data.frame(x = seq(1e4), y = seq(1e4)), aes(x, y)) +
    stat_function(fun = function(x) x) +
    scale_x_log10()
Run Code Online (Sandbox Code Playgroud)

情况2:相比之下,坐标转换发生在统计转换之后;即,该函数首先以原始单位计算,然后在x上进行坐标转换,从而扭曲了该函数:

ggplot(data.frame(x = seq(1e4), y = seq(1e4)), aes(x, y)) +
    stat_function(fun = function(x) x) +
    coord_trans(xtrans = "log10")
Run Code Online (Sandbox Code Playgroud)

...当然,除非对x和y都应用相同的变换:

ggplot(data.frame(x = seq(1e4), y = seq(1e4)), aes(x, y)) +
    stat_function(fun = function(x) x) +
    coord_trans(xtrans = "log10", ytrans = "log10")
Run Code Online (Sandbox Code Playgroud)