Adding a 3rd order polynomial and its equation to a ggplot in r

后端 未结 2 1771
离开以前
离开以前 2020-12-07 17:38

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?

2条回答
  •  盖世英雄少女心
    2020-12-07 18:36

    Part 1: to fit a polynomial, use the arguments:

    • method=lm - you did this correctly
    • formula=y ~ poly(x, 3, raw=TRUE) - i.e. don't wrap this in a call to lm

    The code:

    p + stat_smooth(method="lm", se=TRUE, fill=NA,
                    formula=y ~ poly(x, 3, raw=TRUE),colour="red")
    

    enter image description here


    Part 2: To add the equation:

    • Modify your functionlm_eqn() to correctly specify the data source to lm - you had a closing parentheses in the wrong place
    • Use annotate() to position the label, rather than geom_text

    The 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)
    

    enter image description here

提交回复
热议问题