【发布时间】:2021-12-25 18:30:21
【问题描述】:
我正在尝试添加多项式最佳拟合线,但由于某种原因,它似乎在图上来回绘制。我想知道我应该怎么做才能修复这条线
yhat_pol = lm(age~poly(height,2), data = Loblolly)
yhat_lin = lm(age~height, data = Loblolly)
plot(x=Loblolly$height, y=Loblolly$age, pch=16, xlab = "Height (ft)", ylab = "Age (yr)", main = "Height vs Age of Loblloy Pine Trees")
lines(Loblolly$height, predict(yhat_pol), type="l", col="green", lwd=2)
lines(Loblolly$height, predict(yhat_lin), type="l", col="red", lwd=2)
lines(sort(Loblolly$height), fitted(yhat_lin)[order(Loblolly$height)])
legend("topleft",
legend = c("linear","polynomial"),
col = c("red","green"),
lty = 1, lwd=3)
| height | age | Seed | |
|---|---|---|---|
| 1 | 4.51 | 3 | 301 |
| 15 | 10.89 | 5 | 301 |
| 29 | 28.72 | 10 | 301 |
| 43 | 41.74 | 15 | 301 |
| 57 | 52.70 | 20 | 301 |
| 71 | 60.92 | 25 | 301 |
| 2 | 4.55 | 3 | 303 |
| 16 | 10.92 | 5 | 303 |
| 30 | 29.07 | 10 | 303 |
| 44 | 42.83 | 15 | 303 |
【问题讨论】:
-
您能分享一些您问题中使用的数据吗?试试
dput(Loblolly)或dput(head(Loblolly))。 -
我从 R 中的数据集包中获取了数据集,所以我认为只需输入 Loblolly 就可以了,但我在问题中添加了 head(Lobolly)。
-
你是对的!忘记我的评论。
标签: r plot regression