【问题标题】:Plotting fitted and original data in R, with higher density of x values for fitted在 R 中绘制拟合数据和原始数据,拟合的 x 值密度更高
【发布时间】:2018-03-26 11:58:55
【问题描述】:

我试着在这里搜索了一段时间,但我并没有真正找到解决问题的方法。我想要一种简单的方法来获得拟合模型的方程并将其与我的原始数据一起显示。

这里是目前有效的代码:

#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()?

感谢您的建议!

【问题讨论】:

  • 很好,很好的问题,如果所有的初学者都能清楚地解释事情。顺便说一句,相关文档(predict())有点隐藏,但你可以通过?predict.lm找到它。

标签: r ggplot2 lm


【解决方案1】:

关键不是在你用来制作模型的数据上进行预测,而是在相同范围内生成更密集的数据:

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)

【讨论】:

    【解决方案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])
    

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多