【问题标题】:Boxplot not showing range箱线图不显示范围
【发布时间】:2020-05-11 18:27:08
【问题描述】:

我有预测值,通过:

glm0 <- glm(use ~ as.factor(decision), data = decision_use, family = binomial(link = "logit"))

predicted_glm <- predict(glm0, newdata = decision_use, type = "response", interval = "confidence", se = TRUE)

predict <- predicted_glm$fit
predict <- predict + 1

head(predict)
        1         2         3         4         5         6 
0.3715847 0.3095335 0.3095335 0.3095335 0.3095335 0.5000000 

现在,当我使用 ggplot2 绘制箱线图时,

ggplot(decision_use, aes(x = decision, y = predict)) +
  geom_boxplot(aes(fill = factor(decision)), alpha = .2)

我得到一个箱线图,每个分类变量有一条水平线。如果您查看预测数据,每个分类变量都是相同的,因此是有道理的。

但我想要一个带有范围的箱形图。我怎么能得到那个?当我使用“使用”而不是预测时,我得到的框从一端延伸到另一端(1 到 0)。所以我想不是这样。先感谢您。

为了澄清,predicted_glm 包括 se.fit 值。我想知道如何合并这些。

【问题讨论】:

  • 我想你只需要type = "response",如果你正在寻找0-1范围内的数字(即预测概率)而不是对数赔率,这就是type = "link"将返回的逻辑回归。对数赔率可以是 -Inf 到 +Inf 之间的任何位置
  • @AllanCameron 谢谢。我这样做了,现在这些值看起来更像我的预期。这次真是万分感谢。但是我仍然没有得到方框图的范围.....你知道我怎么能得到它吗?
  • @AllanCameron 或任何其他合适的情节。我所有的自变量都是分类变量。 “使用”是 1 和 0。

标签: r ggplot2 data-science logistic-regression boxplot


【解决方案1】:

在这里做箱线图并没有什么意义。箱线图显示组内连续变量的范围和分布。您的因变量是二元的,因此值都是 0 或 1。由于您要为每个组绘制 预测,因此您的绘图将只有一个点表示每个组的预期值(即概率)组。

您最接近的可能是用 95% 的置信度条绘制预测。

您还没有提供任何示例数据,所以我在这里补一些:

set.seed(100)
df <- data.frame(outcome = rbinom(200, 1, c(0.1, 0.9)), var1 = rep(c("A", "B"), 100))

现在我们将创建模型并使用predictnewdata 参数获取我的预测变量每个级别的预测。我要指定type = "link",因为我想要对数赔率,我还要指定se.fit = TRUE,这样我就可以得到这些预测的标准误差:

mod <- glm(outcome ~ var1, data = df, family = binomial)
prediction <- predict(mod, list(var1 = c("A", "B")), se.fit = TRUE, type = "link")

现在我可以为我的预测计算出 95% 的置信区间:

prediction$lower <- prediction$fit - prediction$se.fit * 1.96
prediction$upper <- prediction$fit + prediction$se.fit * 1.96

最后,我将拟合和置信区间从对数赔率转换为概率:

prediction <- lapply(prediction, function(logodds) exp(logodds)/(1 + exp(logodds)))

plotdf <- data.frame(Group = c("A", "B"), fit = prediction$fit,
                     upper = prediction$upper, lower = prediction$lower)
plotdf
#>   Group  fit     upper      lower
#> 1     A 0.13 0.2111260 0.07700412
#> 2     B 0.92 0.9594884 0.84811360

现在我准备好进行绘图了。我将使用geom_points 作为概率估计,使用geom_errorbars 作为置信区间:

library(ggplot2)

ggplot(plotdf, aes(x = Group, y = fit, colour = Group)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), size = 2, width = 0.5) +
  geom_point(size = 3, colour = "black") + 
  scale_y_continuous(limits = c(0, 1)) + 
  labs(title = "Probability estimate with 95% CI", y = "Probability")

reprex package (v0.3.0) 于 2020-05-11 创建

【讨论】:

  • 这实际上是我几天前最终决定的。谢谢 - 我仍会将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2014-08-27
  • 2021-11-16
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 2015-09-11
相关资源
最近更新 更多