【问题标题】:Multiple logistic regression ggplot with groups带组的多元逻辑回归ggplot
【发布时间】:2021-03-12 19:59:46
【问题描述】:

这有点烦我,所以我希望有人有一个想法。我正在运行一个多元逻辑回归,其中有一个数字预测器和一个分类预测器。我想为模型的逻辑回归制作一个漂亮的 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() 与响应类型一起使用,然后添加一个 geom_line() 和 y = prediction_value。这看起来不错,但不如使用 geom_smooth 平滑。我知道我也可以在更多点上使用 predict() 来平滑它,但这似乎必须有更好的方法来做到这一点。

【问题讨论】:

    标签: r ggplot2 logistic-regression


    【解决方案1】:

    可能是这样的吗?

    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
      )
    
    

    【讨论】:

    • 我仍然想在图中有三个逻辑曲线 - 每个级别的齿轮一个,但要确保它们适合模型,例如它们只是彼此的翻译并且具有相同的斜率。
    【解决方案2】:

    通常我发现如果你试图让 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 日创建

    【讨论】:

    • 我怀疑你可能是对的,但我不禁觉得那里的 geom_lines 看起来比 geom_smooth 制作的平滑函数有点草率。 :(
    • @Matt 它们以相同的方式产生(都使用grid::linesGrob 来画线),所以情况不应该如此。尝试通过增加new_data 数据框中的预测点数或调整线的size 参数来增加“平滑度”。
    • 哦,谢谢!我没有意识到他们都使用了这个 - 我会继续增加预测点的数量。谢谢!
    猜你喜欢
    • 2019-07-22
    • 2014-06-26
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多