简体   繁体   中英

Formatting regression line equation using ggplot2 in R

I am curious how one would edit the following solution from Jayden so that the equation may be formatted y = bx + a or y = bx - a? I wanted to make it look as clean as possible.

  lm_eqn = function(m) {

  l <- list(a = format(coef(m)[1], digits = 2),
      b = format(abs(coef(m)[2]), digits = 2),
      r2 = format(summary(m)$r.squared, digits = 3));

  if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
  } else {
    eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)    
  }

  as.character(as.expression(eq));                 
}

I have tried eliminated in the %.% and that throws up an error and I have tried inverting the order, but am having issues with the syntax in the if/else section of the function. I also would like to make it where the equation is formatted such that the coeff (a) is presented without the negative sign. abs(a) returns |a|. Thanks for any input! It is appreciated!

This follows from another thread( Adding Regression Line Equation and R2 on graph )

If you want it in b*x+a form then just:

if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == 
                 b %.% italic(x) + a*","~~italic(r)^2~"="~r2, l)
  } else {
    eq <- substitute(italic(y) == 
               - b %.% italic(x) + a *"," ~~ italic(r)^2 ~"="~r2, l)  
  }

Writing R expressions requires understanding that there is a syntax rule: token/separator/token, but you can use either "+" or "-" as a unary separator. The upper portion of the plotmath symbol table in ?plotmath has the acceptable separators. Spaces and linefeeds get ignored.

What error are you seeing? This works for me to give bx ± a as requested. You have to move the abs() to the definition of a instead of b and test coef(m)[1] instead of 2...

lm_eqn = function(m) {

  l <- list(a = format(abs(coef(m)[1]), digits = 2),
      b = format(coef(m)[2], digits = 2),
      r2 = format(summary(m)$r.squared, digits = 3));

  if (coef(m)[1] >= 0)  {
    eq <- substitute(italic(y) ==  b %.% italic(x) + a*","~~italic(r)^2~"="~r2,l)
  } else {
    eq <- substitute(italic(y) ==  b %.% italic(x) - a*","~~italic(r)^2~"="~r2,l)    
  }

  as.character(as.expression(eq));                 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM