R ggplot2:物流结果统计平滑,小平面包裹返回';完整';或';子集';glm模型

R ggplot2:物流结果统计平滑,小平面包裹返回';完整';或';子集';glm模型,r,plot,ggplot2,R,Plot,Ggplot2,我正在研究一个逻辑回归模型,该模型具有一个连续预测因子和一个具有多个水平的分类预测因子。我想使用ggplot2并利用facet\u wrap来显示分类预测值的每个级别的回归线。进行此操作时,我注意到,stat\u smooth提供的拟合曲线只考虑特定方面的数据,而不是整个数据集。这是一个很小的差异,但在查看绘图与从predict.glm返回的预测值时,这是一个明显的差异 下面是一个用代码后面的图形重新创建问题的示例 library(boot) # needed for inv.logit

我正在研究一个逻辑回归模型,该模型具有一个连续预测因子和一个具有多个水平的分类预测因子。我想使用
ggplot2
并利用
facet\u wrap
来显示分类预测值的每个级别的回归线。进行此操作时,我注意到,
stat\u smooth
提供的拟合曲线只考虑特定方面的数据,而不是整个数据集。这是一个很小的差异,但在查看绘图与从
predict.glm
返回的预测值时,这是一个明显的差异

下面是一个用代码后面的图形重新创建问题的示例

library(boot)    # needed for inv.logit function
library(ggplot2) # version 0.8.9

set.seed(42)
n <- 100

df <- data.frame(location = rep(LETTERS[1:4], n),
                 score    = sample(45:80, 4*n, replace = TRUE))

df$p    <- inv.logit(0.075 * df$score + rep(c(-4.5, -5, -6, -2.8), n))
df$pass <- sapply(df$p, function(x){rbinom(1, 1, x)}) 

gplot <- ggplot(df, aes(x = score, y = pass)) + 
            geom_point() + 
            facet_wrap( ~ location) + 
            stat_smooth(method = 'glm', family = 'binomial') 

# 'full' logistic model
g <- glm(pass ~ location + score, data = df, family = 'binomial')
summary(g)

# new.data for predicting new observations
new.data <- expand.grid(score    = seq(46, 75, length = n), 
                        location = LETTERS[1:4])

new.data$pred.full <- predict(g, newdata = new.data, type = 'response')

pred.sub <- NULL
for(i in LETTERS[1:4]){
  pred.sub <- c(pred.sub,
    predict(update(g, formula = . ~ score, subset = location %in% i), 
            newdata = data.frame(score = seq(46, 75, length = n)), 
            type = 'response'))
}

new.data$pred.sub <- pred.sub

gplot + 
  geom_line(data = new.data, aes(x = score, y = pred.full), color = 'green') + 
  geom_line(data = new.data, aes(x = score, y = pred.sub),  color = 'red')
library(boot)#inv.logit函数需要
库(ggplot2)#版本0.8.9
种子(42)

n正确的做法是在ggplot2之外拟合模型,然后根据自己的喜好计算拟合值和间隔,并单独传递数据

实现您描述的目标的一种方法如下:

preds <- predict(g, newdata = new.data, type = 'response',se = TRUE)
new.data$pred.full <- preds$fit

new.data$ymin <- new.data$pred.full - 2*preds$se.fit
new.data$ymax <- new.data$pred.full + 2*preds$se.fit  

ggplot(df,aes(x = score, y = pass)) + 
    facet_wrap(~location) + 
    geom_point() + 
    geom_ribbon(data = new.data,aes(y = pred.full, ymin = ymin, ymax = ymax),alpha = 0.25) +
    geom_line(data = new.data,aes(y = pred.full),colour = "blue")
preds