【问题标题】:boxplot with linear fit doesn't use coefficients具有线性拟合的箱线图不使用系数
【发布时间】:2014-10-24 19:27:37
【问题描述】:

我尝试了两个类别的简单箱线图(传输类型为 0 或 1),并添加了线性拟合,并希望它通过箱线图的方式,但这里出了点问题:

linearFit <- lm(mpg~am, data=mtcars)
boxplot(mpg~am, data=mtcars) 
abline(linearFit, lwd=2, col="blue")

linearFit$coefficients
# (Intercept)          am 
#   17.147368    7.244939

但是,这条线远远超出了两个箱线图,而不是通过“类别”0 的截距。如何告诉 R 在基本绘图系统中使用类别均值?

编辑澄清: 所以我只需要一条蓝线,它在这个箱线图中穿过 (0, 17.14) 和 (1, 17.14+7.244),其中变量“am”(传输类型)是一个因子而不是数字变量。 在基础绘图系统中是否有一种简单的方法可以做到这一点?

【问题讨论】:

  • 感谢编辑,Henrik!

标签: r regression


【解决方案1】:

由于am 被视为一个因子,因此am 的系数是向截距的偏移。因此,您必须将其添加到截距中才能获得 am=1 截距。

linearFit <- lm(mpg~am, data=mtcars)
boxplot(mpg~am, data=mtcars, border=1:2 )
abline(h=c(linearFit$coefficients[1], linearFit$coefficients[1]+linearFit$coefficients[2]), col=1:2, lty=2, lwd=2)

此外,am 术语的重要性可以通过与仅包含截距(即“1”)的模型进行比较来测试

linearFit0 <- lm(mpg~1, data=mtcars) # model with intercept only
anova(linearFit0, linearFit)

编辑 - 在箱线图外绘制

plot(x=c(0,1), res$stats[3,], ylim=range(res$stats))
segments(x0=c(0,1), x1=c(0,1), y0=res$stats[2,], y1=res$stats[4,])
abline(linearFit)

Edit2 - 箱线图的移位值

linearFit <- lm(mpg~I(am+1), data=mtcars)
boxplot(mpg~I(am+1), data=mtcars, border=1:2 )
abline(linearFit$coefficients, col=1:2, lty=2, lwd=2)

【讨论】:

  • 您好,感谢您的解释。但是您的代码会产生两条水平线-我需要一条线来遍历每个类别/因素的方式。
  • 这就是你得到的(或者我不完全理解你的问题)——每一行代表 am 因子水平 0 和 1 的平均值。
  • 抱歉,我只需要一条穿过 (0, 17.14) 和 (1, 17.14+7.244) 的蓝线,但这些因素会以某种方式破坏这里的东西
  • 如果你想这样做,我认为你并没有完全理解你的模型的结果 - am 不是一个连续变量,因此斜线是不合适的。
  • 嗯,我明白这条线在 0 和 1 之间没有意义,但它肯定显示了一种趋势,对吧?那么如何首先将其转换为数值变量,然后将 x 轴上的标签设置为 0 和 1(即,如果需要的话,我想伪造数值)
猜你喜欢
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2019-05-09
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 2012-07-29
相关资源
最近更新 更多