Plot two regression equations (or more) on the same graph ggplot

3.2k views Asked by At

I need to display on the same graph two linear regression equations and the coefficients (r, r², p, N). I did this using the facet_grid, but now the two curves can not be displayed separately.

I modified the code that was like facet_grid function:

  equation = function(file) {
  mod = lm(y ~ x,data=file)
  mod_sum = summary(mod)
  formula = sprintf("y= %.3f %+.3f*x", coef(mod)[1], coef(mod)[2])
  r = mod_sum$r.squared
  r2 = sprintf("r2= %.3f", r)
  x  = cor.test(~x + y,data=file)
  r0 = sprintf("r= %.3f", x[4])
  p1 = pf(mod_sum$fstatistic[1],mod_sum$fstatistic[2],mod_sum$fstatistic[3],lower.tail=F)
 p =sprintf("p = %.3f", p1)
n0 = length(mod_sum$residual)
n1 = sprintf("N = %.f", n0)
data.frame(formula=formula, r=r0,r2=r2, p=p,n=n1, stringsAsFactors=FALSE)
}

equation_end = ddply(file, c("outlier"), equation) 

The data of the two regressions are in the same column and are separated by the factor "outlier"

How can I display these equations on the same graph?

1

There are 1 answers

4
Rorschach On BEST ANSWER

You can use annotate to place text on your figure

library(ggplot2)
ggplot(file, aes(x, y, color=outlier)) +
  geom_point() +
  annotate("text", c(-1,-1), c(3,4), label=equation_end$formula)

enter image description here

If you want the text the same color as some lines, try using geom_text,

ggplot(file, aes(x, y, color=outlier)) +
  geom_point() +
  geom_smooth(fill=NA) +
  geom_text(data=equation_end, aes(x=c(-1,-1), y=c(3,4), label=formula), show_guide=F)

enter image description here Data:

library(plyr)
x <- rnorm(100)
file <- data.frame(x=x, y=2*x + rnorm(100), outlier=factor(sample(0:1, 100, rep=T)))
equation_end = ddply(file, c("outlier"), equation)