There are plenty of questions and answers on SO regarding the annotation of a plot to include a linear regression's equation and r-squared. Many are versions of the code from this question, which annotates a ggplot2 plot. I'd like to have the these regression terms to be included as separate lines on the plot. Instead of:
y = b + mx, r2 = 0.xxx
as shown on the plot below, I'd prefer:
y = b + mx
r2 = 0.xxx
Is there a way to use substitute
to produce line breaks? I've attempted to insert an \n
or "\n"
instead of the ","
, but these were not successful. If not, is there another similar method to produce such results? Admittedly, I've been largely unsuccessful in determining the syntax used with the substitute code below. ~
appears to be insert a space, I don't know what the *
does, etc.
# https://stackoverflow.com/q/7549694/1670053
p <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_smooth(method =lm, se=F) + geom_point()
lm_eqn = function(m) {
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));
}
p1 <- p + annotate("text", x = 7.5, y = 100, label = lm_eqn(lm(dist ~ speed, cars)),
colour="black", size = 5, parse=TRUE)