0

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.

enter image description here

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
dorien
  • 5,265
  • 10
  • 57
  • 116

1 Answers1

2

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

Community
  • 1
  • 1
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248