繁体   English   中英

如何更改 R 中最佳拟合线的外观

[英]How to change the appearance of the best fit line in R

我正在尝试添加多项式最佳拟合线,但由于某种原因,它似乎在绘图上来回绘制。 我想知道我应该怎么做才能修好这条线

在此处输入图片说明

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) 
高度 年龄 种子
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

你几乎拥有它。

lines(sort(Loblolly$height), predict(yhat_pol)[order(Loblolly$height)], type="l", col="green", lwd=2)

如果您使用 ggplot2,我认为数据的顺序不会导致这些问题。 在此处输入图片说明

你没有要求它,但这是 - 正如布赖恩蒙哥马利所指出的 - 一个使用ggplot2的解决方案:

library(dplyr)
library(tidyr)
library(ggplot2)


Loblolly %>%
  mutate(age_pred_pol = predict(yhat_pol),
         age_pred_lin = predict(yhat_lin)) %>% 
  ggplot(aes(x = height, y = age)) +
  geom_point() +
  geom_line(aes(y = age_pred_pol, color = "Polynomial Best Fit")) +
  geom_line(aes(y = age_pred_lin, color = "Linear Best Fit")) +
  labs(x = "Height (ft)", y = "Age (yr)", title = "Height vs Age of Loblloy Pine Trees") +
  scale_colour_manual(name = "Prediction",
                      breaks = c("Polynomial Best Fit", "Linear Best Fit"),
                      values = c("red", "green")) +
  theme_bw()

这返回

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM