Skip to content

Instantly share code, notes, and snippets.

@ottadini
Last active July 11, 2017 03:41
Show Gist options
  • Save ottadini/6882677 to your computer and use it in GitHub Desktop.
Save ottadini/6882677 to your computer and use it in GitHub Desktop.
Annotate a ggplot2 plot with regression line equation and R^2
# Source: http://stackoverflow.com/q/7549694/857416
lm_eqn = function(m) {
# Displays regression line equation and R^2 value on plot
# Usage:
# p + annotate("text", x=25, y=300, label=lm_eqn(lm(y ~ x, df)), parse=TRUE)
l <- list(a = format(coef(m)[1], digits = 2),
b = format(abs(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3));
if (coef(m)[2] >= 0) {
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
} else {
eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
}
as.character(as.expression(eq));
}
# base graphics version: http://stackoverflow.com/a/13119440/857416
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment