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?
set.seed(1410)
dsmall<-diamonds[sample(nrow(diamonds), 100), ]
df<-data.frame("x"=dsmall$carat, "y"=dsmall$price)
p <-ggplot(df, aes(x, y))
p <- p + geom_point(alpha=2/10, shape=21, fill="blue", colour="black", size=5)
#Add a loess smoother
p<- p + geom_smooth(method="loess",se=TRUE)
How can I add a 3rd order polynomial? I have tried:
p<- p + geom_smooth(method="lm", se=TRUE, fill=NA,formula=lm(y ~ poly(x, 3, raw=TRUE)),colour="red")
Finally how can I add the 3rd order polynomial equation and the residual to the graph?
I have tried:
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))
}
data.label <- data.frame(x = 1.5,y = 10000,label = c(lm_eqn(df)))
p<- p + geom_text(data=data.label,aes(x = x, y = y,label =label), size=8,family="Times",face="italic",parse = TRUE)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…