Ordering points on a section of R lines

I want to add an inline quadratic anchor string to scatteprlot, but the ordering of the points is somehow messed up.

attach(mtcars)
plot(hp, mpg)
fit <- lm(mpg ~ hp + I(hp^2))
summary(fit)
res <- data.frame(cbind(mpg, fitted(fit), hp))
with(res, plot(hp, mpg))
with(res, lines(hp, V2))

This draws lines all over the place, unlike smooh plotted through a scatterplot. I'm sure this is pretty simple, but I'm a bit puzzled.

enter image description here

+4
source share
1 answer

When building a line, all points are connected in the order in which they were received. It looks like you want to sort the values hpbefore connecting the dots

res <- data.frame(cbind(mpg, fitted(fit), hp))
res <- res[order(hp), ]
with(res, plot(hp, mpg))
with(res, lines(hp, V2))

To obtain

enter image description here

, , , hp, . , ,

php <- seq(min(hp), max(hp), length.out=100)
p <- predict(fit, newdata=data.frame(hp=php))
plot(hp, mpg)
lines(php, p)

enter image description here

+6

All Articles