0

I'm trying to plot a regression line with some data in x and y. I create a function which calculates the coefficients of the line, then I call it in "p" to show the equation in the title.

library(ggplot2)
x <- c(1,2,2,2,3,3,4,5,5,6,6,6,6,7,8,9,9,11,11,11,15,15,16,16,16,16,17,18,18,18)
y <- c(1,2,4,3,3,2,5,4,6,3,7,7,6,7,8,4,5,4,9,9,13,14,15,15,15,16,17,19,19,20)

eq = function(x) {
lm_coef <-list( a = round(coef(x)[2], digits = 2), b = round(coef(x)[1], digits = 2), r2 = round(summary(x)$r.squared, digits = 2));
lm_eq <- substitute(y =  a * x + b )
    as.character(as.ep(lm_eq));
}
p <- ggplot(data=NULL, aes(x=x, y=y)) +
    geom_point() +
    geom_smooth(method=lm, se=FALSE, color="black") +
    scale_y_log10() +
    ggtitle(eq(x))+
    theme(plot.title= element_text(hjust=0.5, size=20))
p

The problem is that I get this error message :

"$ operator is invalid for atomic vectors".

I know that the problem comes from my call in ggtitle(equation(x)) but I don't know how to solve it.

If you have an idea, thanks

jogo
  • 12,469
  • 11
  • 37
  • 42
Wapitix
  • 53
  • 4
  • 2
    You pass `x` as a vector, but want to extract coefficients from it `coef(x)` – pogibas Aug 30 '19 at 09:25
  • In the equation, you'r handling x as an lm object, while it's a vector. Besides, you're creating an object called lm_coef but you didn't use it to build lm_eq. – Nacho Glez Aug 30 '19 at 09:32
  • I changed ìt, now I have `lm_eq <- substitute(a + b, lm_coef)` but I still have an error – Wapitix Aug 30 '19 at 09:41
  • `x` is your vector.. it is not a model! So you are trying to get coefficient from a vector which is meaningless.. In your eq function, use two inputs like `function(x,y)` and then call `coef(lm(y~x))` – maydin Aug 30 '19 at 09:59
  • https://stackoverflow.com/questions/7549694/adding-regression-line-equation-and-r2-on-graph – PeterD Aug 30 '19 at 10:01

1 Answers1

0

I guess you want something like this:

library(ggplot2)
x <- c(1,2,2,2,3,3,4,5,5,6,6,6,6,7,8,9,9,11,11,11,15,15,16,16,16,16,17,18,18,18)
y <- c(1,2,4,3,3,2,5,4,6,3,7,7,6,7,8,4,5,4,9,9,13,14,15,15,15,16,17,19,19,20)
df = as.data.frame(cbind(x,y))

lm_eqn <- function(x,y){
  m <- lm(y ~ x);

  a = format(unname(coef(m)[1]), digits = 2)
  b = format(unname(coef(m)[2]), digits = 2)
  r2 = format(summary(m)$r.squared, digits = 3)

  eq = paste("y = ", a, " + ",b, "* x", "   R² = ", r2)
  as.character(as.expression(eq));
}

p <- ggplot(data=df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth(method=lm, se=FALSE, color="black") +
  scale_y_log10() +
  ggtitle(lm_eqn(x,y))+
  theme(plot.title= element_text(hjust=0.5, size=20))
p

However you should also read the comments above and understand the errors in your code.

PeterD
  • 1,331
  • 12
  • 22