I have plotted the following data with ggplot2 and then add 3rd order polynomial lines for each group consulting the post: Adding a 3rd order polynomial and its equation to a ggplot in r Data:
>lai.se1
DOS DAS N LAI sd se ci
D1 31 24 1.5879167 0.42763230 0.08729008 0.18057328
D1 84 24 4.3241667 0.32478644 0.06629675 0.13714529
D1 113 24 3.7037500 0.34151596 0.06971165 0.14420954
D1 132 24 2.9704167 0.33386380 0.06814966 0.14097832
D1 160 24 0.1879167 0.09868611 0.02014422 0.04167149
D2 35 24 1.7679167 0.18551876 0.03786886 0.07833770
D2 82 24 3.7670833 0.38212767 0.07800148 0.16135836
D2 108 24 3.4104167 0.31431747 0.06415978 0.13272463
D2 126 24 2.7879167 0.35024189 0.07149283 0.14789418
D2 146 24 0.1950000 0.08836682 0.01803780 0.03731404
D3 37 24 1.3179167 0.16378616 0.03343271 0.06916083
D3 83 24 3.5233333 0.29256982 0.05972057 0.12354140
D3 94 24 3.1604167 0.28257326 0.05768002 0.11932022
D3 113 24 2.4587500 0.44131535 0.09008312 0.18635113
D3 134 24 0.2758333 0.09536733 0.01946677 0.04027009
p<-ggplot(lai.se1, aes(x=DAS, y=LAI, colour=DOS)) +
geom_errorbar(aes(ymin=LAI-sd, ymax=LAI+sd), colour ="black", size =.3, width=1,
position=position_dodge(.9)) +
geom_point(size=1, shape=21, fill=FALSE)+ theme_bw()
p + stat_smooth(method="lm", se=TRUE, fill=NA, ## to add polynomial lines
formula=y ~ poly(x, 3, raw=TRUE))
Plot:
## Add equation in the plot
lm_eqn = function(lai.se1){
m=lm(y ~ poly(x, 3), lai.se1)#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(lai.se1), hjust=0, size=8,
family="Times", face="italic", parse=TRUE)
Error:
Error in model.frame.default(formula = y ~ poly(x, 3), data = lai.se1, :
variable lengths differ (found for 'poly(x, 3)')
But as I tried to place the equations using similar function mentioned the above linked post, it gave an error of variable length. I am not really good at writing new functions in r and need your help to solve it. Please help.