带组的多元逻辑回归 ggplot

Multiple logistic regression ggplot with groups

这让我有点恼火,所以我希望有人能出主意。我是 运行 一个多元逻辑回归,其中有一个数值预测变量和一个分类预测变量。我想为模型的逻辑回归制作一个漂亮的 ggplot(没有交互项,所以曲线应该只是彼此的翻译)。例如:

data("mtcars")

library(ggplot2)

glm(data = mtcars, vs ~ mpg + as.factor(gear))

创建模型。一个想法是

ggplot(data = mtcars, aes(x = mpg, y = vs, color = as.factor(gear))) +
  geom_point() +
  geom_smooth(
    method = "glm",
    method.args = list(family = "binomial"),
    se = F
  )

但这为每个组创建了一个单独的逻辑模型,这是一个不同的模型。我想出的最好办法是使用带有响应类型的 predict(),然后添加带有 y = prediction_value 的 geom_line()。这看起来不错,但它不像使用 geom_smooth 那样流畅。我知道我也可以在更多点上使用 predict() 来平滑它,但这似乎必须有更好的方法来做到这一点。

也许是这样的?

ggplot(data = mtcars, aes(x = mpg, y = vs)) +
  geom_point( aes(color = as.factor(gear))) +
  geom_smooth(
    method = "glm",
    method.args = list(family = "binomial"),
    se = F
  )

通常我发现如果你试图让 ggplot 做一些非标准的事情(即不常见或不寻常的转换),如果你只计算你想要绘制的内容,那么它会更容易和更快地工作,然后使用简单的 ggplot 语法绘制它。

library(ggplot2)

fit <- glm(vs ~ mpg + factor(gear), data = mtcars, family = binomial)

new_data <- data.frame(gear = factor(rep(3:5, each = 100)),
                       mpg  = rep(seq(10, 35, length.out = 100), 3))

new_data$vs <- predict(fit, newdata = new_data, type = "response")


ggplot(data = mtcars, 
       aes(x = mpg, y = vs, color = as.factor(gear))) +
  geom_point() +
  geom_line(data = new_data, size = 1)

reprex package (v0.3.0)

于 2020-11-30 创建