繁体   English   中英

ggplot2 和 GLM:绘制预测概率

[英]ggplot2 and GLM: plot a predicted probability

我正在寻找有关如何使用以下数据制作 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)

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

#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)

绘图

我已经绘制了结果变量与一个预测变量“statusquo”的图。 您可以通过更改 predictorVec 的索引来适应其他预测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)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM