title: Adding a 3rd order polynomial and its equation to a ggplot in r
body: <p>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?</p>
  
  <pre><code>set.seed(1410)
  dsmall&lt;-diamonds[sample(nrow(diamonds), 100), ]
  df&lt;-data.frame("x"=dsmall$carat, "y"=dsmall$price)
  
  p &lt;-ggplot(df, aes(x, y)) 
  p &lt;- p + geom_point(alpha=2/10, shape=21, fill="blue", colour="black", size=5)
  
  #Add a loess smoother
  p&lt;- p + geom_smooth(method="loess",se=TRUE)
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/drpth.png" alt="enter image description here"></p>
  
  <p>How can I add a 3rd order polynomial? I have tried:</p>
  
  <pre><code>p&lt;- p + geom_smooth(method="lm", se=TRUE, fill=NA,formula=lm(y ~ poly(x, 3, raw=TRUE)),colour="red")
  </code></pre>
  
  <p>Finally how can I add the 3rd order polynomial equation and the residual to the graph? 
  I have tried:</p>
  
  <pre><code> lm_eqn = function(df){
      m=lm(y ~ poly(x, 3, df))#3rd degree polynomial
      eq &lt;- 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 &lt;- data.frame(x = 1.5,y = 10000,label = c(lm_eqn(df)))
  
  
  p&lt;- p + geom_text(data=data.label,aes(x = x, y = y,label =label), size=8,family="Times",face="italic",parse = TRUE)
  </code></pre>