R线图中点的顺序 [英] Ordering of points in R lines plot

查看:118
本文介绍了R线图中点的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向scatteprlot添加二次拟合的拟合线,但是点的顺序有点混乱.

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.

推荐答案

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

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))

获得

此外,为了获得更平滑的线条,您可能会考虑在除观察到的hp值以外的其他位置进行预测.拟合模型后,就可以

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)

这篇关于R线图中点的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆