在同一图表上绘制两个回归方程(或更多)ggplot

时间:2015-06-23 22:39:30

标签: r ggplot2 regression linear-equation

我需要在同一图表上显示两个线性回归方程和系数(r,r²,p,N)。我使用facet_grid执行此操作,但现在两条曲线无法单独显示。

我修改了类似facet_grid函数的代码:

  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) 

两个回归的数据在同一列中,并以因子“异常值”

分隔

如何在同一图表上显示这些方程?

1 个答案:

答案 0 :(得分:3)

您可以使用annotate在图片上放置文字

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

如果您希望文字与某些线条的颜色相同,请尝试使用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 数据:

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) 
相关问题