r – 黄土和glm用ggplot2绘图

我试图使用来自泰坦尼克号的数据来绘制来自二元选择glm的模型预测与经验概率.为了显示不同阶级和性别之间的差异,我正在使用分面,但我有两件事我无法弄清楚.首先,我想将黄土曲线限制在0和1之间,但如果我将选项ylim(c(0,1))添加到图的末尾,则黄土曲线周围的色带会被切断如果它的一侧超出界限则关闭.我要做的第二件事是从每个方面的最小x值(从glm预测的概率)到最大x值(在同一个方面内)和y = 1画一条线,以便显示glm预测概率.

#info on this data http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3info.txt
load(url('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.sav'))
titanic <- titanic3[ ,-c(3,8:14)]; rm(titanic3)
titanic <- na.omit(titanic) #probably missing completely at random
titanic$age <- as.numeric(titanic$age)
titanic$sibsp <- as.integer(titanic$sibsp)
titanic$survived <- as.integer(titanic$survived)

training.df <- titanic[sample(nrow(titanic), nrow(titanic) / 2), ]
validation.df <- titanic[!(row.names(titanic) %in% row.names(training.df)), ]


glm.fit <- glm(survived ~ sex + sibsp + age + I(age^2) + factor(pclass) + sibsp:sex,
               family = binomial(link = "probit"), data = training.df)

glm.predict <- predict(glm.fit, newdata = validation.df, se.fit = TRUE, type = "response")

plot.data <- data.frame(mean = glm.predict$fit, response = validation.df$survived,
                        class = validation.df$pclass, sex = validation.df$sex)

require(ggplot2)
ggplot(data = plot.data, aes(x = as.numeric(mean), y = as.integer(response))) + geom_point() +
       stat_smooth(method = "loess", formula = y ~ x) +
       facet_wrap( ~ class + sex, scale = "free") + ylim(c(0,1)) + 
       xlab("Predicted Probability of Survival") + ylab("Empirical Survival Rate")

最佳答案 第一个问题的答案是使用coord_cartesian(ylim = c(0,1))而不是ylim(0,1);这是一个适度的常见问题解答.

对于你的第二个问题,可能有一种方法可以在ggplot中完成,但我更容易从外部汇总数据:

g0 <- ggplot(data = plot.data, aes(x = mean, y = response)) + geom_point() +
             stat_smooth(method = "loess") +
             facet_wrap( ~ class + sex, scale = "free") + 
             coord_cartesian(ylim=c(0,1))+
             labs(x="Predicted Probability of Survival",
                  y="Empirical Survival Rate")

(我通过消除一些默认值并使用实验室来略微缩短您的代码.)

ss <- ddply(plot.data,c("class","sex"),summarise,minx=min(mean),maxx=max(mean))
g0 + geom_segment(data=ss,aes(x=minx,y=minx,xend=maxx,yend=maxx),
                  colour="red",alpha=0.5)
点赞