【问题标题】:Plotting nonlinear regression in R在 R 中绘制非线性回归
【发布时间】:2016-07-09 15:58:13
【问题描述】:

我是 R 新手,一直在尝试为某些数据拟合非线性模型,但没有成功。最后,我在 Excel 中添加了多项式趋势线,并尝试绘制我得到的函数 - 由于某种原因,该函数不适合我在 R 中的数据。 我尝试了简单的 geom_smooth,但实现了“笨重”的线条,我想要一个平滑的线条。 我在一个图中有 6 个样本,这是其中一个的数据,包括 Excel 获得的函数和我尝试绘制它的尝试。我确信有更好的方法 - 我还需要在输出中获取拟合函数。

datax <- c(0, 21.3, 30, 46.3, 72)
datay <- c(0, 0.008723333, 0.016253333, 0.039896667, 0.079893333)
data <- data.frame(datax, datay)
x <- seq(0, 0.01, length.out = 72)
poly.fit <- function(x) 1E-5*x^2+0.0002*x
ggplot(data, aes(x=datax, y=datay)) +
  geom_point() +
  stat_function(fun=poly.fit)

【问题讨论】:

    标签: r ggplot2 regression non-linear-regression


    【解决方案1】:

    嗯,这个函数并不完全适合数据。 运行代码和poly.fit(46.3) 后,它返回0.0306969 不是.03989

    问题在于方程本身。如果您确实想在 R 中创建一个与数据完美匹配的函数,那么有一个名为 polynomial interpolation 的原则几乎表明,如果您想要完美地拟合模型中的项,您需要与模型中的项一样多的点。所以,如果你想匹配点,你可以使用:

     m <- lm(datay ~ poly(datax,4))   # poly() fits the polynomial with 4+1 terms
     summary(m)                       # displays coefficients
    

    获得系数后,您可以像以前一样重新创建函数,这应该适合线以完美匹配您的点(只要您适合足够的多项式项!)。

    编辑: 这是显示您想要的可重现代码的示例

    library(ggplot2)
    datax <- c(0, 21.3, 30, 46.3, 72)
    datay <- c(0, 0.008723333, 0.016253333, 0.039896667, 0.079893333)
    data <- data.frame(datax, datay)
    
    # This is another approach to the fitting using I()
    m <- lm(datay ~ datax + I(datax^2) + I(datax^3) + I(datax^4))
    
    x <- seq(0, 72, by = .1)
    poly.fit = function(x){       
        as.numeric(m$coefficients[1]) +
        as.numeric(m$coefficients[2])*x +
        as.numeric(m$coefficients[3])*x^2 + 
        as.numeric(m$coefficients[4])*x^3 + 
        as.numeric(m$coefficients[5])*x^4
    }  #This way you dont have to copy and paste coefficients
    
    ggplot(data, aes(x=datax, y=datay)) +
      geom_point() +
      stat_function(fun=poly.fit)
    

    【讨论】:

    • 执行系数的精度提供了更好的拟合:poly.fit
    • 谢谢@cgage,不过我在重新创建函数时遇到了一些麻烦。我不确定系数是否正确,或者我是否正确使用它们,模型已经偏离了。你能解释一下吗?
    • 没问题,我编辑了我的答案以使事情变得更容易。希望这是你想要的。
    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 2017-03-17
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多