首页 > 解决方案 > 将拟合线添加到多个 ggplot 输出

问题描述

我正在使用以下代码使用来自的逻辑模型绘制每个回归量X_train与响应变量的关系wonglm()

require(reshape2)
require(ggplot2)
regressors = melt(X_train[2:16], id.vars='won')
ggplot(regressors) +
  geom_jitter(aes(value,won, colour=variable),) + 
  geom_smooth(aes(value,won, colour=variable), method="glm", method.args = list(family = "binomial")) +
  facet_wrap(~variable, scales="free_x") 

输出

我认为该geom_smooth()命令会将拟合的逻辑回归线添加到每个图中,但我似乎无法让它工作。我也尝试将“ data=X_train”传递给命令。任何建议表示赞赏,谢谢。

标签: rggplot2graphicsglm

解决方案


我认为您的 TRUE/FALSE 需要转换为 1/0。

这是一个mtcars数据示例:

library(dplyr); library(ggplot2)

# doesn't work
regressors <- pivot_longer(mtcars, -mpg)

# still doesn't work
regressors <- pivot_longer(mtcars, -mpg) %>% 
                mutate(mpg = (mpg > median(mpg)))
# Warning messages:
# 1: Computation failed in `stat_smooth()`:
# y values must be 0 <= y <= 1 
# ...


# works
regressors <- pivot_longer(mtcars, -mpg) %>% 
                mutate(mpg = (mpg > median(mpg)) %>% as.numeric())

ggplot(regressors) +
  geom_jitter(aes(value,mpg, colour=name), height = 0.05) + 
  geom_smooth(aes(value,mpg, colour=name), method="glm", method.args = list(family = "binomial")) +
  facet_wrap(~name, scales="free_x") 

在此处输入图像描述


推荐阅读