Last active
July 11, 2017 03:41
-
-
Save ottadini/6882677 to your computer and use it in GitHub Desktop.
Annotate a ggplot2 plot with regression line equation and R^2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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