How to add regression line equation and R^2 on the ggplot.

My code is as follows:

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

Jun 1, 2018 6,628 views

## 1 answer to this question.

Below is one solution:

```# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: http://goo.gl/K4yh

lm_eqn <- function(df){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 2),
b = format(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_eqn(df), parse = TRUE)```

• 8,240 points

## How to change font size of text and axes on R plots ?

To change the font size of text ...READ MORE

## How can I print string and variable contents on the same line using R?

There are two options for doing so.  You ...READ MORE

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

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

## Changing the legend title in ggplot

Hi, you can also try guides() to ...READ MORE

## How to order bars in a bar graph using ggplot2?

The key to ordering is to set ...READ MORE

## How to create a box-plot using “plotly” in R?

You can use this command to create ...READ MORE