使用变换轴时如何从 stat_smooth 中提取二次拟合

问题描述 投票:0回答:1

我正在尝试提取二次拟合线,以便我可以计算出 y = 0.1 处的 x 坐标,但由于 y 轴上的对数变换,lm() 和 stat_smooth 给了我不同的拟合。

最小数据集:

> xvals <- c(0,1,2,2.5,3,5,7.5,10)
> yvals <- c(1,0.65,0.425,0.45,0.26,0.085,0.0121667,0.000675)
> df <- cbind.dataframe(xvals,yvals)
> 
> ggplot(df, aes(x = xvals, y = yvals))+
> stat_smooth(method= 'lm', formula = y~poly(x,2), se = F, color = 'blue')+
> stat_function(fun=function(x) 0.93389 + -0.25608 *x + 0.01663*x^2, color = 'green')+
> geom_point(color = 'blue', shape = 22, size = 3)+
> geom_hline(yintercept = 0.1)+
> geom_vline(xintercept = 4.675868)+
> scale_y_continuous(trans = 'log10')

stat_function 坐标源自 lm(我也做了 poly(x,2) raw = T 并且它给出了相同的坐标。

> lm(df, formula = yvals ~ I(xvals^2) + I(xvals))

我通过求解方程画出了黑线,因此当 y = 0.1 时,lm 给出 x = 4.7。然而,正如您所看到的,这与 stat_smooth 线不一致,因为方程略有不同。

如果我对 y 轴进行对数变换,则线条将绘制在彼此之上,并且 stat_smooth 线在 4.7 处交叉。

我从一些搜索中了解到,这是由 ggplot 在多项式拟合之前转换数据引起的,除非我刚刚犯了一个巨大的错误,在这种情况下,欢迎任何帮助。

有谁知道如何转换放入 lm 中的数据或导出 stat_smooth 用于获取 stat_smooth 与 y = 0.1 相交的坐标的方程。

r ggplot2 lm
1个回答
0
投票

问题是您使用的 log10 trans 未定义负值(如果未修改)。 Trans 将

fun
中的
stat_function()
返回值替换为
log10(0.93389 + -0.25608 *x + 0.01663*x^2)
。请参阅此示例:

ggplot(df, aes(x = xvals, y = yvals))+
stat_smooth(method= 'lm', formula = y~poly(x,2), se = F, color = 'blue')+
  stat_function(fun=function(x) log10(0.93389 + -0.25608 *x + 0.01663*x^2), color = 'green')+
geom_point(color = 'blue', shape = 22, size = 3)+
geom_hline(yintercept = 0.1)+
geom_vline(xintercept = 4.675868)

如果将

trans = 'log10'
替换为
trans = 'pseudo_log'
,您将得到匹配的曲线:

ggplot(df, aes(x = xvals, y = yvals))+
stat_smooth(method= 'lm', formula = y~poly(x,2), se = F, color = 'blue')+
  stat_function(fun=function(x) 0.93389 + -0.25608 *x + 0.01663*x^2, color = 'green')+
geom_point(color = 'blue', shape = 22, size = 3)+
geom_hline(yintercept = 0.1)+
geom_vline(xintercept = 4.675868)+
scale_y_continuous(trans = 'pseudo_log')

© www.soinside.com 2019 - 2024. All rights reserved.