[英]ggplot2 geom_smooth, extended model for method=lm
我想使用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))
同
ggplot(df, aes(x=pred, y=outcome, color=factor)) +
geom_point(aes(color=factor)) +
geom_smooth(method = "lm") +
theme_bw()
由于color=factor
选项,我生成的拟合线基本上是线性模型lm(outcome ~ pred*factor, df)
的输出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()
这导致:
我的问题:有没有办法生成后一个利用geom_smooth
图? 我知道在geom_smooth
有一个formula =
- 选项,但是我不能做出类似于formula = y ~ x + factor
或formula = y ~ x + color
(我定义的color = factor
)的工作。
这是一个非常有趣的问题。 geom_smooth
对于允许多变量的自定义模型如此“抵抗”的主要原因可能是它仅限于生成二维曲线; 因此,其参数设计用于处理二维数据(即公式=响应变量〜自变量)。
获得所需内容的技巧是使用geom_smooth
的mapping
参数,而不是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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.