3 views

I wonder how to add a regression line equation and R^2 on the ggplot. My code is

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

Any help will be highly appreciated.

by

geom_text(x = 25, y = 300, label = lm_eq(df), parse = TRUE)

Where the following function finds the line equation and value of r^2.

lm_eq <- function(df){

m <- lm(y ~ x, df);

eq <- substitute((y) == a + b %.% (x)*","~~(r)^2~"="~r2,

list(a = format(unname(coef(m)[1]), digits = 2),

b = format(unname(coef(m)[2]), digits = 2),

r2 = format(summary(m)\$r.squared, digits = 3)))

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

}

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

lm_eq <- function(df){

m <- lm(y ~ x, df);

eq <- substitute((y) == a + b %.% (x)*","~~(r)^2~"="~r2,

list(a = format(unname(coef(m)[1]), digits = 2),

b = format(unname(coef(m)[2]), digits = 2),

r2 = format(summary(m)\$r.squared, digits = 3)))

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

}

p1 <- p + geom_text(x = 25, y = 300, label = lm_eq(df), parse = TRUE)

p1

Output: