在R中绘制拟合数据和原始数据,使用更高密度的x值进行拟合
问题描述:
我试着在这里搜索了一段时间,但是我没有真正找到解决我的问题的方法。我想要一个简单的方法来获得拟合模型的方程,并将其与我的原始数据一起显示。在R中绘制拟合数据和原始数据,使用更高密度的x值进行拟合
这里是到目前为止的工作代码:
#the dataframe:
library(ggplot2)
df<-data.frame(x=c(0,3,5,7,9,14),y=c(1.7,25.4,185.5,303.9,255.9,0.0))
#fitting a third degree polinomial model
fit1<- lm(y~poly(x, 3, raw=TRUE),data = df)
#plotting fitted and original values
ggplot(df, aes(x, y))+
geom_point()+
geom_line(aes(x, y=predict(fit1)), col=2)
下面的剧情结果[红色表示预测值,黑色=原始数据]:
现在,我试着与我的原始数据点相比,可以更好地掌握模型的实际外观,因为我希望稍后计算线下面积。
我试图通过提取从FIT1系数通过调用
coef(fit1)
和打字的近似系数的方程
x1<-seq(0:14)
eq<- 20.35*x1+6.64*x1^2-0.58*x1^3-10.84
在没有任何简单的方法为“提取物”的F(X )= x + x^2 + c等函数从一个模型中显示出来并且以高密度(0到14之间的无限x值)和原始值一起显示?也许使用geom_line()或stat_function()?
感谢您的任何建议!
答
的关键不是预测的,你用来做模型,而是产生在同一范围内的更高密度的数据的数据:
x <- seq(from = min(df$x), to = max(df$x), by = 0.1)
下面是完整的代码:
library(ggplot2)
df <- data.frame(x = c(0, 3, 5, 7, 9, 14), y = c(1.7, 25.4, 185.5, 303.9, 255.9, 0.0))
fit1 <- lm(y ~ poly(x, 3, raw = TRUE), data = df)
生成密集的数据:
predf <- data.frame(x = seq(from = min(df$x), to = max(df$x), by = 0.1))
预测Y开致密数据:
predf$y <- predict(fit1, predf)
简介:
ggplot(df, aes(x, y))+
geom_point()+
geom_line(data= predf, aes(x, y ), col=2)
答
对于那些有兴趣,我发现了一些很不错的代码在这里:How to calculate the area under each end of a sine curve 提取功能和计算AUC,并适应这里的例子:
#get the function from the model
poly3fnct <- function(x){
(fnct <- fit1$coeff[1]+
fit1$coeff[2]* x +
fit1$coeff[3]* x^2 +
fit1$coeff[4]* x^3) +
return(fnct)
}
#function to find the roots
manyroots <- function(f,inter){
roots <- array(NA, inter)
for(i in 1:(length(inter)-1)){
roots[i] <- tryCatch({
return_value <- uniroot(f,c(inter[i],inter[i+1]))$root
}, error = function(err) {
return_value <- -1
})
}
retroots <- roots[-which(roots==-1)]
return(retroots)
}
#find the roots or x values for y = 0
roots <- manyroots(poly3fnct,seq(0,14))
roots
#integrate function
integrate(poly3fnct, roots[1],roots[2])
尼斯和提出的问题,如果只有所有的第一时间解释的东西这很清楚。顺便说一下,相关文档('predict()')有点隐藏,但是你可以用'predict.lm'找到它。 – AkselA