0

I want to add an equation of a linear model to a plot with ggplot2. The question has been asked manty times, but I have a problem with the following code - a problem not occurred before - so I think this is not a duplicate question.

I used many times the following code, from this post in stackoverflow

library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
  geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
  geom_point()
p

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));                 
}
p1 = p + geom_text(aes(x = 25, y = 300, label = lm_eqn(lm(y ~ x, df))), parse = TRUE)
p1

The problem is that in the plot now the coefficients of equation are surrounded by c(): enter image description here

giannic
  • 91
  • 5

1 Answers1

1

It seems that code doesn't properly remove the names from the vector of coefficients. Try using this version instead

lm_eqn <- function(m) {

  l <- list(a = format(unname(coef(m)[1]), digits = 2),
            b = format(unname(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 just added in a few unname() calls.

MrFlick
  • 195,160
  • 17
  • 277
  • 295