我绘制了以下数据并添加了黄土平滑器。我想在图中添加一个三阶多项式及其方程(包括残差)。有什么建议吗?
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)
如何添加三阶多项式?我试过了:
p<- p + geom_smooth(method="lm", se=TRUE, fill=NA,formula=lm(y ~ poly(x, 3, raw=TRUE)),colour="red")
最后,如何将三阶多项式方程和残差添加到图中?我试过了:
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)