我是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)
好吧,该功能不能完全适合数据。运行代码后,poly.fit(46.3)
它返回0.0306969
不是.03989
问题在于方程本身。如果您确实想在R中创建一个与数据完全匹配的函数,则有一个称为多项式插值的原理,该原理几乎表明如果要完美拟合,则需要与模型中的项一样多的点。因此,如果您想匹配这些点,可以使用:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句