ggplot2 geom_smooth,方法的扩展模型= lm

Dri*_*ies 17 r ggplot2

我想用来geom_smooth从某个线性回归模型中得到拟合线.

在我看来,公式只能采取x,y而不是任何额外的参数.

为了更清楚地显示我想要的东西:

library(dplyr)
library(ggplot2)
set.seed(35413)
df <- data.frame(pred = runif(100,10,100),
           factor = sample(c("A","B"), 100, replace = TRUE)) %>%
  mutate(
    outcome = 100 + 10*pred + 
    ifelse(factor=="B", 200, 0) + 
    ifelse(factor=="B", 4, 0)*pred +
    rnorm(100,0,60))
Run Code Online (Sandbox Code Playgroud)

ggplot(df, aes(x=pred, y=outcome, color=factor)) +
  geom_point(aes(color=factor)) +
  geom_smooth(method = "lm") +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

我生产的装配线,由于color=factor选项,基本上是线性模型的输出lm(outcome ~ pred*factor, df)

在此输入图像描述

但是,在某些情况下,我更喜欢将线条作为不同模型拟合的输出,例如lm(outcome ~ pred + factor, df),我可以使用以下内容:

fit <- lm(outcome ~ pred+factor, df)
predval <- expand.grid(
  pred = seq(
    min(df$pred), max(df$pred), length.out = 1000),
  factor = unique(df$factor)) %>%
  mutate(outcome = predict(fit, newdata = .))

ggplot(df, aes(x=pred, y=outcome, color=factor)) +
  geom_point() +
  geom_line(data = predval) +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

这导致:

在此输入图像描述

我的问题:有没有办法生成后一个利用geom_smooth相反的图?我知道有一个formula =- 选项,geom_smooth但我不能做像(formula = y ~ x + factorformula = y ~ x + color我定义的color = factor)工作.

Mar*_*ell 6

这是一个非常有趣的问题.可能导致geom_smooth允许多变量自定义模型如此"抗拒"的主要原因是它仅限于生成二维曲线; 因此,其参数设计用于处理二维数据(即公式=响应变量〜自变量).

获取所请求内容的技巧是使用mapping内部参数geom_smooth而不是formula.正如您在查看文档时看到的那样,formula只允许您指定模型的数学结构(例如线性,二次等).相反,mapping参数允许您直接指定新的y值 - 例如可以使用的自定义线性模型的输出predict().

请注意,默认情况下,inherit.aes设置为TRUE,因此您的绘制回归将由分类变量适当地着色.这是代码:

# original plot
plot1 <- ggplot(df, aes(x=pred, y=outcome, color=factor)) +
  geom_point(aes(color=factor)) +
  geom_smooth(method = "lm") +
  ggtitle("outcome ~ pred") +
  theme_bw()

# declare new model here
plm <- lm(formula = outcome ~ pred + factor, data=df)

# plot with lm for outcome ~ pred + factor
plot2 <-ggplot(df, aes(x=pred, y=outcome, color=factor)) +
  geom_point(aes(color=factor)) +
  geom_smooth(method = "lm", mapping=aes(y=predict(plm,df))) +
  ggtitle("outcome ~ pred + factor") +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述