Search code examples
rggplot2scatter-plotnon-linear-regression

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 the following code to show my linear model's line, how do i add the polynomial model (pm1) to this?

I am looking for an output similar to the image below. enter image description here

I'm open to abandoning the ggplot if needed

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. I am trying plot the lines of both a linear and non linear model to a scattergraph based off of this.

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

Solution

  • 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 enter image description here

    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:

    enter image description here