I have a data frame df
which I split into segments of 10 rows. On each of these I apply a quadratic regression. What I want is to be able to include all the stat_function
instances onto the original plot p1
. I thought to try p1<-p1 + stat_function(fun=f, color='blue')
. The code below works without error but the resulting plot only includes one blue quadratic. How can I achieve the desired plot?
library(ggplot2)
g <- function(x){x*(x-1)*(x-2)}
x<-rnorm(500)
error <- rnorm(500)
y<-g(x)+error
df<-data.frame(x=x,y=y)
p1<-ggplot(df, aes(x=x, y=y)) +
geom_point(color='red')
p1
for (i in 0:10){
df2<-df[(1+10*i):(10+10*i),]
m<-lm(y~poly(x,2,raw=TRUE),df2)
b<-m$coefficients
f<-function (x) {b[1]+b[2]*x+b[3]*x^2}
p1<-p1 + stat_function(fun=f, color='blue')
}
p1