R线图中点的排序

phi*_*sch 6 plot regression r points

我想在散点图中添加一个二次拟合的拟合线,但点的排序在某种程度上搞砸了.

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))
Run Code Online (Sandbox Code Playgroud)

这样可以在整个地方绘制线条,而不是通过散点图进行渲染.我确信这很简单,但我有点难过.

在此输入图像描述

MrF*_*ick 10

绘制线条时,所有点都按接收顺序连接.看起来您想hp在连接点之前对值进行排序

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

要得到

在此输入图像描述

此外,为了获得更平滑的线,您可以考虑预测除了hp您观察到的值之外的其他点.适合您的模型后,您就可以做到

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

在此输入图像描述