ggplot2和GLM:绘制预测概率

约翰·梭哈

我正在寻找有关如何使用以下数据制作ggplot的帮助。有几个关于stackoverflow的示例,但是它们要复杂得多,我很难弄清楚。

library(car)
data(Chile)
Chile$yes <- with(Chile, ifelse(vote == "Y", 1, ifelse(vote=="N", 0, NA))) 
Chile<-na.omit(Chile)

logit1 <- glm(yes ~ statusquo + age + income + sex, data = Chile, family=binomial(link="logit")) 


inject1 <- data.frame(statusquo=mean(na.omit(Chile$statusquo)), income=mean(Chile$income), sex="F", age=mean(Chile$age))
predict1 <- predict(logit1, newdata=inject1, type="response", se.fit=TRUE)


inject2 <- data.frame(statusquo=mean(na.omit(Chile$statusquo)), income=mean(Chile$income), sex="M", age=mean(Chile$age))
predict2 <- predict(logit1, newdata=inject2, type="response", se.fit=TRUE)

结果变量为“是”,我想x的性别会有所不同-我想绘制这些预测。

在此先感谢您的时间和帮助!

沉默多古德

对于逻辑回归的典型“ S”形图,您需要更多的预测,而不是当前正在使用的点预测

install.packages("caret")

library(car)
library(ggplot2)

data(Chile)
Chile$yes <- with(Chile, ifelse(vote == "Y", 1, ifelse(vote=="N", 0, NA))) 
Chile<-na.omit(Chile)

为了获得更多的预测,我们使用包中的createDataPartition函数将数据集分为训练和测试数据集caret

#split Chile dataset into train for fitting and test for prediction purpose
set.seed(42)
trainIndex = createDataPartition(Chile$yes, p=0.75,list=FALSE)


trainChile = Chile[trainIndex,]
testChile = Chile[-trainIndex,]

#fit logit model
fitLogit <- glm(yes ~ statusquo + age + income + sex, data = trainChile, family=binomial(link="logit")) 

#predict on test data
predLogit <- predict(fitLogit, newdata=testChile, type="response", se.fit=TRUE)

绘图

我已经绘制了结果变量与一个预测变量“状态”的图表。您可以通过更改以下指标来将其调整为其他预测变量predictorVec

#if fit value is > 0.5, we consider voting outcome as "YES/1 else  "NO"/0

predictorVec = c("statusquo","age","income","sex")

x = predictorVec[1]

plotObj= data.frame(predictor=testChile[,x],outcome=ifelse(predLogit$fit>0.5,1,0))

gg = ggplot(plotObj, aes(x=predictor, y= outcome)) + geom_point() + 
  stat_smooth(method="glm", method.args=list(family="binomial"), se=FALSE) + 
  ggtitle(paste0("Prediction for predictor:",x)) +
  theme(plot.title = element_text(size=14, face="bold"))
print(gg)

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章