我是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)
答案 0 :(得分:3)
那么,该功能并不完全适合数据。
运行代码后,poly.fit(46.3)
会返回0.0306969
<{1}},而不是.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)