在 R 中绘制非线性回归

Plotting nonlinear regression in R

我是 R 的新手,一直在尝试将非线性模型拟合到某些数据,但没有成功。最后,我在 Excel 中添加了一条多项式趋势线,并尝试绘制我得到的函数——由于某种原因,该函数不适合我在 R 中的数据。 我尝试了简单的 geom_smooth,但得到了一条 "bulky" 线,我想要一个平滑的线。 我在一个图中有 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)

嗯,这个函数并不完全符合数据。 在 运行 代码和 poly.fit(46.3) 之后 returns 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)