Messy plot when plotting predictions of a polynomi

2019-01-09 20: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