【问题标题】:Plot two regression equations (or more) on the same graph ggplot在同一张图 ggplot 上绘制两个回归方程(或更多)
【发布时间】:2015-06-24 08:06:55
【问题描述】:

我需要在同一张图上显示两个线性回归方程和系数 (r, r², p, N)。我是用 f​​acet_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) 

两个回归的数据在同一列,用因子“离群值”隔开

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

【问题讨论】:

  • 你能举个例子reproducible吗?像dput(equation_end) 这样的东西或者如果不是太大的话会很有帮助......

标签: r ggplot2 regression linear-equation


【解决方案1】:

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

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

如果您希望文本与某些行颜色相同,请尝试使用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)

数据:

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) 

【讨论】:

  • 按照你的方式。我使用粘贴来匹配系数。但是,这有点令人困惑,需要与线条的颜色相关联才能变好。也许使用 geom_text。但是还是不行
  • 我不确定您的意思,您希望文本颜色与线条颜色相同吗?
  • 没错。因为这样我就知道它指的是哪组数据。当我使用 geom_text 时只能显示其中一个方程
  • 谢谢你,这样看起来就可以了!我只是定位方程
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
相关资源
最近更新 更多