Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
830 views
in Technique[技术] by (71.8m points)

ggplot2 - 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...