ggplot2中的图形GLM,其中x变量是分类的

问题描述 投票:3回答:1

我需要在ggplot2中绘制logit回归的预测概率。基本上,我试图通过同一图表中的每个处理条件绘制一个glm图。但是,我对如何看到我的treat变量(即我感兴趣的x)是绝对的感到非常困惑。这意味着当我尝试使用ggplot绘制治疗效果图时,我只是得到一堆点0,1和2但没有线。

我的问题是......在这种情况下,我如何绘制logit预测线?提前致谢!

set.seed(96)
df <- data.frame(
  vote = sample(0:1, 200, replace = T),
  treat = sample(0:3, 200, replace = T))

glm_output <- glm(vote ~ as.factor(treat), data = df, family = binomial(link = "logit"))

predicted_vote <- predict(glm_output, newdata = df, type = "link", interval = "confidence", se = TRUE)
df <- cbind(df, data.frame(predicted_vote))
r graph ggplot2 glm
1个回答
3
投票

由于解释变量treat是分类的,如果你使用boxplot代替如下更有意义:

ggplot(df, aes(x = treat, y = predicted_prob)) +
  geom_boxplot(aes(fill = factor(treat)), alpha = .2)

enter image description here

如果你想通过glm在一些其他解释变量的不同值上看到预测的概率,你可以试试这个:

ggplot(df, aes(x = treat, y = predicted_prob)) +
  geom_boxplot(aes(fill = factor(treat)), alpha = .2) + facet_wrap(~gender)

enter image description here

# create age groups 
df$age_group <- cut(df$age, breaks=seq(0,100,20))

ggplot(df, aes(x = treat, y = predicted_prob)) +
  geom_boxplot(aes(fill = factor(treat)), alpha = .2) + facet_grid(age_group~gender)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.