将二次回归线添加到现有的 ggplot R

问题描述

我已经将一个线性模型和一个多项式模型拟合到同一个数据帧上,并且想在同一个散点图上绘制两条线。

我有以下代码显示我的线性模型的线条,我如何将多项式模型 (pm1) 添加到其中?

我正在寻找类似于下图的输出

enter image description here

如果需要,我愿意放弃 ggplot

ggplot(A1,aes(x = PopMns,y = Freq)) +
  geom_point() +
  stat_smooth(method = "lm",col = "red") +
  geom_line()

这是我正在使用的数据框。我正在尝试将线性和非线性模型的线绘制成基于此的散点图。

year Freq PopTotal   PopMns
1 1970  611  3700437 3700.437
2 1971  436  3775760 3775.760
3 1972  515  3851651 3851.651
4 1973  436  3927781 3927.781
5 1974  531  4003794 4003.794
6 1975  685  4079480 4079.480

解决方法

试试这个:

#Code
ggplot(A1,aes(x = PopMns,y = Freq)) +
  geom_point() +
  stat_smooth(method = "lm",col = "red",se=F) +
  stat_smooth(method = "lm",col = "blue",formula = y~poly(x,2),se=F) +
  geom_line()

结果如下 enter image description here

有没有办法用散点代替黑线?

更新:试试这个,使用你的数据:

library(ggplot2)
#Code
ggplot(A1,se=F,2))

输出:

enter image description here