Skip to content

Instantly share code, notes, and snippets.

@adamhsparks
Last active May 17, 2019 16:47
Show Gist options
  • Select an option

  • Save adamhsparks/e299e6d1beb82ed258c1052050d63bc5 to your computer and use it in GitHub Desktop.

Select an option

Save adamhsparks/e299e6d1beb82ed258c1052050d63bc5 to your computer and use it in GitHub Desktop.
Add p-value, R2 and equation to linear models in ggplot2
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
m <- lm(y ~ x, data = df)
summary(m)
# see that p <2e-16
# function to create the text equation
lm_eqn <- function(df, lm_object) {
eq <-
substitute(
italic(y) == a + b %.% italic(x) * "," ~ ~ italic(r) ^ 2 ~ "=" ~ r2,
list(
a = format(coef(lm_object)[1], digits = 2),
b = format(coef(lm_object)[2], digits = 2),
r2 = format(summary(lm_object)$r.squared, digits = 3),
p = p_value, digits = 2
)
)
as.character(as.expression(eq))
}
# get the equation object in a format for use in ggplot2
eqn <- lm_eqn(df, m)
# plot everything
ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", formula = y ~ x) +
geom_point() +
annotate("text",
x = 25,
y = 300,
label = "italic(p) <2e-16",
parse = TRUE) +
annotate("text",
x = 25,
y = 315,
label = eqn,
parse = TRUE) +
theme_minimal()
## References ------------------------------------------------------------------
# https://stackoverflow.com/questions/7549694/adding-regression-line-equation-and-r2-on-graph
# https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
# https://stackoverflow.com/questions/5587676/pull-out-p-values-and-r-squared-from-a-linear-regression
# https://ggplot2.tidyverse.org/reference/annotate.html
@eeusha

eeusha commented May 8, 2019

Copy link
Copy Markdown

gives this error
Error in lm_eqn(df, m) : object 'p_value' not found

@Balamur7

Copy link
Copy Markdown

The definition of lm_object is also missing.

Can you add this information?

Thanks in advance,
Norman

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment