Add regression line equation and R 2 on graph

0 votes

I wonder how to add 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

Thanks in advance

Mar 22, 2022 in Machine Learning by Nandini
• 5,480 points
2,944 views

1 answer to this question.

0 votes

Let us look at one of the possible solutions

# EQUATION AND R-SQUARED Get AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
    m <- lm(y ~ x, df);
    equation <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(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(equation));
}
p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

Output

Supercharge Your Skills with Our Machine Learning Course!

answered Mar 23, 2022 by Dev
• 6,000 points

Related Questions In Machine Learning

0 votes
1 answer

How to add random and/or fixed effects into cloglog regression in R

The standard glm function can be used ...READ MORE

answered Apr 13, 2022 in Machine Learning by anonymous
446 views
0 votes
1 answer
0 votes
1 answer

R: Force regression coefficients to add up to 1

b1 + b2 = 1 Let us fit ...READ MORE

answered Mar 23, 2022 in Machine Learning by Nandini
• 5,480 points
1,403 views
0 votes
1 answer

How to create excellent examples in R?

An excellent example must consist of the ...READ MORE

answered Apr 10, 2018 in Data Analytics by kappa3010
• 2,090 points

edited Apr 12, 2018 by kappa3010 503 views
0 votes
1 answer

How to plot side-by-side Plots with ggplot2 in R?

By Using gridExtra library we can easily ...READ MORE

answered Apr 16, 2018 in Data Analytics by DeepCoder786
• 1,720 points

edited Jun 9, 2020 by MD 8,523 views
+1 vote
1 answer

How to change fill color in each facet using ggplot2?

You can map the facetting variable to ...READ MORE

answered May 8, 2018 in Data Analytics by kappa3010
• 2,090 points
24,702 views
0 votes
1 answer
0 votes
1 answer

Can I draw a regression line and show parameters using scatterplot with a pandas dataframe?

There isn't a parameter for DataFrame.plot(). Seaborn, ...READ MORE

answered Mar 7, 2022 in Machine Learning by Dev
• 6,000 points
2,463 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP