Messy plot when plotting predictions of a polynomial regression using lm() in R

陌路散爱 提交于 2019-12-17 10:05:16

问题


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.


回答1:


You need order():

P <- predict(quadratic.model)
plot(y~x)
reorder <- order(x)
lines(x[reorder], P[reorder])

My answer here is related: Problems displaying LOESS regression line and confidence interval



来源:https://stackoverflow.com/questions/38700240/messy-plot-when-plotting-predictions-of-a-polynomial-regression-using-lm-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!