I have plotted the following data and added a loess smoother. I would like to add a 3rd order polynomial and its equation (incl. the residual) to the plot. Any advice?
Part 1: to fit a polynomial, use the arguments:
method=lm - you did this correctlyformula=y ~ poly(x, 3, raw=TRUE) - i.e. don't wrap this in a call to lmThe code:
p + stat_smooth(method="lm", se=TRUE, fill=NA,
formula=y ~ poly(x, 3, raw=TRUE),colour="red")

Part 2: To add the equation:
lm_eqn() to correctly specify the data source to lm - you had a closing parentheses in the wrong placeannotate() to position the label, rather than geom_textThe code:
lm_eqn = function(df){
m=lm(y ~ poly(x, 3), df)#3rd degree polynomial
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 2),
b = format(coef(m)[2], digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq))
}
p + annotate("text", x=0.5, y=15000, label=lm_eqn(df), hjust=0, size=8,
family="Times", face="italic", parse=TRUE)
