简体   繁体   中英

Ordering of points in R lines plot

I want to add a fitted line of a quadratic fit to a 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, as opposed to the smooh fit through the scatterplot. I'm sure this is pretty straightforward, but I'm a little stumped.

在此处输入图像描述

When you plot a line, all the points are connected in the order they were received. Looks like you want to sort your hp values before connecting the points

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

to get

在此处输入图像描述

Also, to get a smoother line, you might considering predicting at points other than just the hp values you observed. After you fit your model, you can do

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM