2

I am unable to plot a linear model text onto the plot without the "c()" characters around my intercept and slope.

I am trying the top solution from this previous question: Adding Regression Line Equation and R2 on graph

df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)

# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
  m <- lm(y ~ x, df);
  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 <- ggplot(data = df, aes(x = x, y = y, label=y))+
  geom_smooth(method="lm", se=FALSE)+
  geom_point()

ymax <- max(df$y)* 0.95
xmean <- mean(df$x)

p1 <- p + geom_text(x = xmean, y = ymax, label = lm_eqn(df), parse = TRUE)
p1

ggplot

Please any help will be greatly appreciated!

Cheers,

0 Answers0