简体   繁体   English

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

[英]Add quadratic regression line to existing ggplot R

I have fit a linear model and a polynomial model onto to same dataframe and would like to plot both lines on the same scattergraph. I have fit a linear model and a polynomial model onto to same dataframe and would like to plot both lines on the same scattergraph.

I have the following code to show my linear model's line, how do i add the polynomial model (pm1) to this?我有以下代码来显示我的线性模型的线,如何将多项式 model (pm1) 添加到此?

I am looking for an output similar to the image below.我正在寻找类似于下图的 output。 在此处输入图像描述

I'm open to abandoning the ggplot if needed如果需要,我愿意放弃 ggplot

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

This is the dataframe i am working with.这是我正在使用的 dataframe。 I am trying plot the lines of both a linear and non linear model to a scattergraph based off of this.我正在尝试 plot 线性和非线性 model 的线到基于此的散点图。

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

Try with this:试试这个:

#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()

This results in the following这导致以下结果在此处输入图像描述

Is there a way to have the scatter points instead of the black line?有没有办法让散点代替黑线?

Update: Try this, using your data:更新:试试这个,使用你的数据:

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

Output: Output:

在此处输入图像描述

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

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