如何在R中绘制拟合多项式?

sim*_*ple 0 r polynomials

我有一个parametric polynomial regressionin R,我像这样适合我的数据:

poly_model <- lm(mydataframef$y ~ poly(mydataframe$x,degree=5))
Run Code Online (Sandbox Code Playgroud)

mydf显然包含yx。然后我像这样绘制它

plot(mydataframe$x, mydataframe$y, xlab='regressor or predictor variable polynomial regression', ylab='outcome or label')
Run Code Online (Sandbox Code Playgroud)

然后我想添加拟合的多项式,所以我执行以下操作:

abline(poly_model)
Run Code Online (Sandbox Code Playgroud)

这给了我一个警告: Warning message: In abline(poly_model) : only using the first two of 6 regression coefficients

当然,情节完全不正常,因为正如承诺的那样,它只使用前两个,即截距和斜率。当我只有一个预测变量时,为什么只使用前两个系数?所以,无论如何,情节应该是二维的?使困惑。谢谢。

The*_*aya 6

这是答案,

poly_model <- lm(mpg ~ poly(hp,degree=5), data = mtcars)

x <- with(mtcars, seq(min(hp), max(hp), length.out=2000))
y <- predict(poly_model, newdata = data.frame(hp = x))

plot(mpg ~ hp, data = mtcars)
lines(x, y, col = "red")
Run Code Online (Sandbox Code Playgroud)

输出图是,

在此处输入图片说明