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
```

Mar 22, 2022 2,306 views

## 1 answer to this question.

Let us look at one of the possible solutions

```# EQUATION AND R-SQUARED Get AS STRING
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)), digits = 2),
b = format(unname(coef(m)), 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)
``` Supercharge Your Skills with Our Machine Learning Course!

• 6,000 points

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

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

## Ignore the NaN and do the linear regression on remaining values

Yes, you can do this using statsmodels: import ...READ MORE

## difference between a cost function and the gradient descent equation in logistic regression?

Cost function is a way to evaluate ...READ MORE

## R: Force regression coefficients to add up to 1

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

## How to create excellent examples in R?

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

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

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

+1 vote

## How to change fill color in each facet using ggplot2?

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

## Selecting only p-value and r.squared value from linear regression result

You can use the \$ symbol to ...READ MORE