【问题标题】:Geom_smooth - linear regression through x-axis interceptGeom_smooth - 通过 x 轴截距的线性回归
【发布时间】:2020-10-28 17:08:03
【问题描述】:

我想在 ggplot2 中使用“geom_smooth”强制通过特定 x 轴交叉点进行线性回归:

geom_smooth(aes(x = x, y = y), method = "lm", formula = y ~ x)

直观地说,选择 x 轴截距,可以使用公式 y = a * (x - b) + c。 在“公式”代码中实现这一点,例如:

 geom_smooth(aes(x = x, y = y), method = "lm", formula = y ~ x - 5)

不起作用。

【问题讨论】:

标签: r ggplot2 regression


【解决方案1】:

我不确定仅使用 geom_smooth 是否可以做到这一点。但是,您可以在 ggplot2 调用之外预测回归,使用偏移量来设置所需的截距并随后绘制它。

例如:

set.seed(1)

# Generate some data
x <- 1:10
y <- 3 + 2*x + rnorm(length(x), 0, 2)

# Simple regression
z_1 <- lm(y ~ x)
# Regression with no intercept
z_2 <- lm(y ~ x + 0)
# Regression with intercept at (0,3) - the 'true' intercept
z_3 <- lm(y ~ x + 0, offset=rep(3, length(x)))

# See the coefficients
coef(z_1)
#(Intercept)           x 
#   2.662353    2.109464 
coef(z_2)
#     x 
#2.4898 
coef(z_3)
#       x 
#1.775515 

# Combine into one dataframe
df <- cbind.data.frame(x,y,predict(z_1),predict(z_2), predict(z_3))

# Plot the three regression lines
library(ggplot2)
ggplot(df) + geom_point(aes(x,y)) +
             geom_line(aes(x,predict(z_1)), color = "red") +
             geom_line(aes(x,predict(z_2)), color = "blue") +
             geom_line(aes(x,predict(z_3)), color = "green") +
             scale_x_continuous(limits = c(0,10)) +
             scale_y_continuous(limits = c(0,30))

【讨论】:

    【解决方案2】:

    您需要对已锁定的 x 截距使用 offset 函数。这是通过 geom_smoothmethod.args 参数传递的,因为并非所有平滑方法都可以使用该参数。

    您还需要指定 orientation 参数来确认您有一个 x 截距,而不是 y 截距。

    我还指定了要绘制的平滑点的数量 (n) 以及要匹配的重复偏移量——不确定这是否是绝对必要的。

    肯定有一些体操,但希望它会有所帮助。

    library("tidyverse")
    mtcars %>%
      ggplot(aes(disp, hp)) +
      geom_point() +
      geom_smooth(method = "lm", 
                  orientation = "y", 
                  formula = y ~ x + 0, 
                  color= "blue", 
                  se = FALSE, 
                  n = nrow(mtcars),
                  method.args=list(offset=rep(100, nrow(mtcars))),
                  fullrange = TRUE) +
      scale_x_continuous(limits =c(0, 600)) 
    #> Warning: Removed 5 rows containing missing values (geom_smooth).
    

    reprex package (v0.3.0) 于 2020 年 7 月 8 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2016-03-04
      • 2019-05-27
      • 2016-08-31
      • 1970-01-01
      • 2018-06-11
      相关资源
      最近更新 更多