0

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?

j_3265
  • 207
  • 3
  • 12
  • Can you make your example [reproducible](http://stackoverflow.com/q/5963269/903061)? Something like `dput(equation_end)` or would help a lot if it's not too big... – Gregor Thomas Jun 23 '15 at 22:50

1 Answers1

3

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) 
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Followed by your way. I used paste to match the coefficients. However, it was a little confusing, needed to be associated with the colors of the lines to get good. Perhaps using the geom_text. But still did not work – j_3265 Jun 23 '15 at 23:47
  • I'm not sure what you mean, you want the text colored the same as the lines? – Rorschach Jun 24 '15 at 00:00
  • That's right. Because this way I know which set of data it refers to. When I use the geom_text can only display one of the equations – j_3265 Jun 24 '15 at 00:07
  • Thank you, this way it looks like it worked! I'm just positioning the equation – j_3265 Jun 24 '15 at 00:46