I have the following ggplot2 code that plots multiple polynomial fits with various degrees:
library(ggplot2)
set.seed(1234)
n = 400
x = rnorm(n, sd=0.4)
y = -x + 2*x^2 - 3*x^3 + rnorm(n,sd=0.75)
df = data.frame(x=x,y=y)
deg = c(1,2,3,10)
cols = c("red","green","blue","orange")
ggplot(df, aes(x=x,y=y)) +
geom_point() +
geom_smooth(method = "lm", formula= y~poly(x,deg[1]), se=F, col=cols[1]) +
geom_smooth(method = "lm", formula= y~poly(x,deg[2]), se=F, col=cols[2]) +
geom_smooth(method = "lm", formula= y~poly(x,deg[3]), se=F, col=cols[3]) +
geom_smooth(method = "lm", formula= y~poly(x,deg[4]), se=F, col=cols[4])
I would like to avoid repeating the geom_smooth line for every degree. But I can't figure out how to get geom_smooth to understand a dynamic degree passed through a variable. Is there a more elegant solution to the above? It would be nice to also automatically change the colors without the need to explicitly pass the cols vector. (Default color scheme is fine).
I have tried to use as.formula(paste0("y~poly(x,",deg[i],")")) through a loop without much luck (and loops don't seem to be the right approach with ggplot.)
