rregressionpredictquadratic-curve

How to create prediction line for Quadratic Model


I am trying to create a quadratic prediction line for a quadratic model. I am using the Auto dataset that comes with R. I had no trouble creating the prediction line for a linear model. However, the quadratic model yields crazy looking lines. Here is my code.

# Linear Model
plot(Auto$horsepower, Auto$mpg,
     main = "MPG versus Horsepower",
     pch = 20)

lin_mod = lm(mpg ~ horsepower,
             data = Auto)
lin_pred = predict(lin_mod)


lines(
  Auto$horsepower, lin_pred,
  col = "blue", lwd = 2
)


# The Quadratic model
Auto$horsepower2 = Auto$horsepower^2
quad_model = lm(mpg ~ horsepower2,
                data = Auto)
quad_pred = predict(quad_model)

lines(
  Auto$horsepower,
  quad_pred,
  col = "red", lwd = 2
)

I am 99% sure that the issue is the prediction function. Why can't I produce a neat looking quadratic prediction curve? The following code I tried does not work—could it be related?:

quad_pred = predict(quad_model, data.frame(horsepower = Auto$horsepower))

Thanks!


Solution

  • The issue is that the x-axis values aren't sorted. It wouldn't matter if was a linear model but it would be noticeable if it was polynomial. I created a new sorted data set and it works fine:

    library(ISLR) # To load data Auto
    
    # Linear Model
    plot(Auto$horsepower, Auto$mpg,
         main = "MPG versus Horsepower",
         pch = 20)
    
    lin_mod = lm(mpg ~ horsepower,
                 data = Auto)
    lin_pred = predict(lin_mod)
    
    
    lines(
      Auto$horsepower, lin_pred,
      col = "blue", lwd = 2
    )
    
    
    # The Quadratic model
    Auto$horsepower2 = Auto$horsepower^2
    
    # Sorting Auto by horsepower2
    Auto2 <- Auto[order(Auto$horsepower2), ]
    quad_model = lm(mpg ~ horsepower2,
                    data = Auto2)
    
    
    quad_pred = predict(quad_model)
    
    
    lines(
      Auto2$horsepower,
      quad_pred,
      col = "red", lwd = 2
    )