如何使用ggplot2在log odd scale上绘制逻辑回归

时间:2017-09-28 03:50:04

标签: r ggplot2 logistic-regression

我试图在对数奇数量表中绘制逻辑回归的结果。

load(url("https://github.com/bossaround/question/raw/master/logisticregressdata.RData"))

ggplot(D, aes(Year, as.numeric(Vote), color = as.factor(Male))) +
  stat_smooth( method="glm", method.args=list(family="binomial"), formula = y~x + I(x^2), alpha=0.5, size = 1, aes(fill=as.factor(Male))) +
  xlab("Year") 

但是这个图是0~1的比例。我想这是概率尺度(如果我错了,请纠正我)?

我真正想要的是将它绘制在对数奇数刻度上,正如逻辑回归报告之前将其转换为概率。

理想情况下,我希望在控制外国之后,通过男性,在这样的模型中绘制投票和年份之间的关系:

   Model <-  glm(Vote ~ Year + I(Year^2) + Male + Foreign, family="binomial", data=D)

我可以根据summary(Model)手动绘制线条,但我也想绘制置信区间。

我在网上找到的文件第44页上的图像:http://www.datavis.ca/papers/CARME2015-2x2.pdf。我将有一个二次曲线。

谢谢!

3 个答案:

答案 0 :(得分:2)

要绘制具有多个变量的模型的预测,应该制作模型,预测新数据以生成预测并绘制

Model <-  glm(Vote ~ Year + I(Year^2) + Male + Foreign, family="binomial", data=D)
for_pred = expand.grid(Year = seq(from = 2, to = 10, by = 0.1), Male = c(0,1), Foreign = c(0,1)) #generate data to get a smooth line

for_pred = cbind(for_pred, predict(Model, for_pred, type = "link", se.fit= T)) 
#if the probability scale was needed: `type = "response`

library(ggplot2)
ggplot(for_pred, aes(Year, fit, color = as.factor(Male))) +
  geom_line() +
  xlab("Year")+
  facet_wrap(~Foreign)  + #important step - check also how it looks without it
  geom_ribbon(aes(ymax = fit + se.fit, ymin = fit - se.fit, fill = as.factor(Male)), alpha = 0.2) 

#omit the color by `color = NA` or by `inherit.aes = F` (if like this, one should provide the data and full `aes` mapping for  geom_ribbon). 
#If geom_ribbon should not have a mapping, specify `fill` outside of `aes` like: `fill = grey80`.

enter image description here

查看库sjPlot

答案 1 :(得分:2)

使用realloc中的augmented()进一步回答:

broom()

给出了:

enter image description here

答案 2 :(得分:0)

您的方法是正确的,但您需要使用已建立的模型来预测值:

ModelPredictions <- predict(Model , type="response")

之后,您可以使用ggplot进行绘图:

ggplot(D, aes(x=ModelPredictions , y=D$Vote )) +
  geom_point()  +  stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial)) +  facet_wrap( ~ Foreign)