There are several references that come close, but my lines() is producing multiple arcs instead of just one nonlinear curve. It looks like a hammock with a bunch of unwanted lines. How do you generate a simple nonlinear line? Dataset available as Auto.csv at 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
lines
plots the data in whatever order it happens to be in. As a result, if you don't sort by the x-value first, you'll get a mess of lines going back and forth as the x-value jumps back and forth from one row to the next. Try this, for example:
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)
To get a nice curve, sort by horsepower
first:
curve.dat = data.frame(x=Auto$horsepower, y=predict(lm.fit2))
curve.dat = curve.dat[order(curve.dat$x),]
lines(curve.dat, col=4)
Whereas, if you don't sort by horsepower
, here's what you get:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments