2016-03-29 20 views
3

いくつかの参考文献がありますが、私のlines()はただ1つの非線形曲線の代わりに複数の弧を生成しています。それは不必要な線の束とハンモックのように見えます。どのように単純な非線形線を生成しますか? Auto.csvとして利用可能なデータセットhttp://www-bcf.usc.edu/~gareth/ISL/data.htmlRで、非線形曲線をプロットする

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 

答えて

3

linesであることを起こるものは何でも順にプロットデータを。あなたが最初のx値でソートしていない場合、結果として、あなたは前後に行くなどのラインの混乱を取得しますx値はある行から次の行へ前後にジャンプします。例えば、これを試してみてください:

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) 

enter image description here

あなたはhorsepowerでソートしていない場合は、ここで何がだ、一方で取得:

enter image description here

1

最初にデータフレームをソートすることを心配したくない場合は、代わりにggplotを使用します。

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") 

enter image description here

3

あなたの多項式適合のためのpolyを使用する必要があります。それはあなたがあなたのモデルに合うようにしたい式やラインの種類を選ぶことができます有用な方法geom_smoothを持っています。その後、predictcurveを使用することができます。

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) 

resulting plot

これもnlsフィットで動作します。

+0

poly()の提案に感謝します。 – Orknie

関連する問題