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 in Machine Learning by Nandini
• 5,480 points
178 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
answered Mar 23 by Dev
• 6,000 points

Related Questions In Machine Learning

0 votes
0 answers

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

Update question on treatment of one variable ...READ MORE

Apr 11 in Machine Learning by Dev
• 6,000 points
37 views
0 votes
1 answer
0 votes
1 answer
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 235 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 7,711 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
20,706 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 in Machine Learning by Dev
• 6,000 points
207 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP