在 R 中使用 lm() 绘制多项式回归的预测时的混乱图 [英] Messy plot when plotting predictions of a polynomial regression using lm() in R
本文介绍了在 R 中使用 lm() 绘制多项式回归的预测时的混乱图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用 R 中的 lm 构建二次模型:
I am building a quadratic model with lm in R:
y <- data[[1]]
x <- data[[2]]
x2 <- x^2
quadratic.model = lm(y ~ x + x2)
现在我想在图上同时显示预测值和实际值.我试过这个:
Now I want to display both the predicted values and the actual values on a plot. I tried this:
par(las=1,bty="l")
plot(y~x)
P <- predict(quadratic.model)
lines(x, P)
但是这条线都弯弯曲曲地出现了.也许这与它是二次方的事实有关?谢谢你的帮助.
but the line comes up all squiggely. Maybe it has to do with the fact that it's quadratic? Thanks for any help.
推荐答案
你需要order()
:
P <- predict(quadratic.model)
plot(y~x)
reorder <- order(x)
lines(x[reorder], P[reorder])
我在这里的回答是相关的:显示 LOESS 回归线和置信区间的问题
My answer here is related: Problems displaying LOESS regression line and confidence interval
这篇关于在 R 中使用 lm() 绘制多项式回归的预测时的混乱图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文