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

R ggplot2中的图形GLM,其中x变量为分类变量,r,graph,ggplot2,glm,R,Graph,Ggplot2,Glm,我需要在ggplot2中绘制logit回归的预测概率。本质上,我试图通过同一个图中的每个处理条件来绘制glm。然而,由于我的treat变量(即我感兴趣的x)是分类变量,我对如何实现这一点感到非常困惑。这意味着,当我尝试使用ggplot绘制治疗效果图时,我只在0、1和2处获得一系列点,但没有线条 我的问题是。。。在这种情况下,如何绘制logit预测线?提前谢谢 set.seed(96) df <- data.frame( vote = sample(0:1, 200, replace =

我需要在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))
set.seed(96)

df由于解释变量
treat
是分类变量,如果您使用箱线图,则更有意义,如下所示:

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

如果您想通过
glm
查看一些其他解释变量的不同值的预测概率,您可以尝试以下方法:

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

#创建年龄组
df$年龄组
# 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)