我正在尝试为二次模型创建二次预测线。我正在使用 R 附带的自动数据集。为线性模型创建预测线没有问题。然而,二次模型会产生看起来很疯狂的线条。这是我的代码。
# 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
)
我 99% 确定问题出在预测函数上。为什么我不能生成一个整洁的二次预测曲线?我尝试的以下代码不起作用 - 它可能相关吗?:
quad_pred = predict(quad_model, data.frame(horsepower = Auto$horsepower))
谢谢!