Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)

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.

1 Answer

0 votes
by
edited by

To add a regression line equation and value of R^2 on your graph, add the following to your plot:

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

}

In your case:

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:

image

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...