【问题标题】:How to fit intercept into particular value in ggplot linear model graph?如何将截距拟合到 ggplot 线性模型图中的特定值?
【发布时间】:2019-09-13 14:17:00
【问题描述】:

我想在 R 中使用 ggplot 生成分解与时间图,代码如下:

ggplot(data=deco, aes(x = week, y = mass, group=interaction(treatment,habitat),
                      colour=habitat, linetype=treatment)) +   
 geom_point() +  
 theme_classic() + 
 geom_smooth(method='lm',formula=y~x)

因为最初的垫料重量是 5 克,所以我预计所有的生产线都会在第 0 周从 5 克开始。然而,我意识到所有的线都有不同的起点。我试图找到任何解决方案来快速处理它们,但所有方法对我来说都不起作用。如果你们中的任何人都可以解决这个问题,那就太好了。

【问题讨论】:

  • 请发布一个可重现的例子。
  • 使用单个组,您可以执行 formula = y ~ x + 0method.args = list(offset = rep(5, nrow(data))) 但如果您的组大小不同,这将很困难——太糟糕了lm 不会回收偏移量长度 1. 一个简单的解决方法可能是转换数据,使截距为0(即从响应中减去 5)并拟合没有截距的模型。然后,您可以在 y 比例上使用变换,以便标记正确。
  • 谢谢,Gregor,我最终通过从响应变量数据中减去 5 解决了这个问题。

标签: r ggplot2 lm intercept


【解决方案1】:

正如 Gregor 所指出的,这并不是微不足道的,因为组大小是未知的,geom_smooth 有点受限。有两个选项,可以在ggplot 之外安装您的模型。或者抑制截距,移动 y 并重新标记您的轴。

ggplot(mtcars, aes(wt, drat, col = factor(am))) + 
  geom_point() + 
  geom_smooth(method = 'lm') +
  xlim(0, 6)


Intercept <- 5
ggplot(mtcars, aes(wt, drat - Intercept, col = factor(am))) + 
  geom_point() + 
  geom_smooth(method = 'lm', formula = y ~ x + 0) +
  scale_y_continuous(labels = function(x) x + Intercept) +
  xlim(0, 6)

【讨论】:

  • 哇 - 不要以为我见过有人使用 drat 而不是 mpg 作为响应。但是对于 OP 的例子来说,这个比例很好。 (该方法的很好的演示:)
  • 我想要更接近原点的东西! :)
猜你喜欢
  • 1970-01-01
  • 2018-01-02
  • 2018-01-12
  • 2019-11-19
  • 1970-01-01
  • 2014-05-24
  • 2016-06-26
  • 2021-04-14
相关资源
最近更新 更多