【问题标题】:in R, plot a nonlinear curve在 R 中,绘制非线性曲线
【发布时间】:2016-03-29 03:38:34
【问题描述】:

有几个参考文献很接近,但我的 lines() 产生了多条弧线,而不仅仅是一条非线性曲线。它看起来像一个吊床,上面有一堆不需要的线条。如何生成简单的非线性线?数据集以 Auto.csv 形式提供,地址为 http://www-bcf.usc.edu/~gareth/ISL/data.html。

    library(ISLR)
    data(Auto)
    lm.fit1=lm(mpg~horsepower,data=Auto) #linear
    lm.fit2=lm(mpg~horsepower+I(horsepower^2),data=Auto) #add polynomial
    plot(Auto$horsepower,Auto$mpg,col=8,pch=1)
    abline(lm.fit1,col=2)       #linear fit
    lines(Auto$horsepower,predict(lm.fit2),col=4)  #attempt at nonlinear

【问题讨论】:

    标签: r plot lines


    【解决方案1】:

    lines 以数据发生的任何顺序绘制数据。因此,如果您不先按 x 值排序,您将得到一堆乱七八糟的线,因为 x -value 从一行到下一个来回跳转。试试这个,例如:

    plot(c(1,3,2,0), c(1,9,4,0), type="l", lwd=7)
    lines(0:3, c(0,1,4,9), col='red', lwd=4)
    

    要获得漂亮的曲线,请先按horsepower 排序:

    curve.dat = data.frame(x=Auto$horsepower, y=predict(lm.fit2))
    curve.dat = curve.dat[order(curve.dat$x),]
    
    lines(curve.dat, col=4)  
    

    然而,如果您不按 horsepower 排序,您会得到以下结果:

    【讨论】:

      【解决方案2】:

      您应该使用poly 进行多项式拟合。然后您可以将curve 与predict 一起使用:

      lm.fit2 = lm(mpg ~ poly(horsepower, 2, raw = TRUE), data = Auto) #fit polynomial
      #curve passes values to x, see help("curve")
      curve(predict(lm.fit2, newdata = data.frame(horsepower = x)), add = TRUE, col = 4) 
      

      这也适用于 nls 拟合。

      【讨论】:

      • 感谢 poly() 的建议。
      【解决方案3】:

      如果您不想先对数据框进行排序,另一种方法是使用ggplot。它有一个有用的方法geom_smooth,可以让您选择要适合模型的公式和线类型:

      library(ISLR)
      library(ggplot2)
      data(Auto)
      
      ggplot(Auto, aes(mpg, horsepower)) + 
        geom_point() + 
        geom_smooth(method="lm", formula = y~x, se=FALSE)+
        geom_smooth(method="lm", formula = y~x+I(x^2), se=FALSE, colour="red")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-09
        • 2021-05-08
        • 2011-07-18
        • 2012-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多