Plot polynomial regression curve in R

psteelk picture psteelk · Apr 28, 2014 · Viewed 70.2k times · Source

I have a simple polynomial regression which I do as follows

attach(mtcars)
fit <- lm(mpg ~ hp + I(hp^2))

Now, I plot as follows

> plot(mpg~hp)
> points(hp, fitted(fit), col='red', pch=20)

This gives me the following

Plot of mpg versus hp

Fitted Values

I want to connect these points into a smooth curve, using lines gives me the following

> lines(hp, fitted(fit), col='red', type='b')

Line plot

What am I missing here. I want the output to be a smooth curve which connects the points

Answer

Davide Passaretti picture Davide Passaretti · Apr 28, 2014

Try:

lines(sort(hp), fitted(fit)[order(hp)], col='red', type='b') 

Because your statistical units in the dataset are not ordered, thus, when you use lines it's a mess.