lme4模型显示交互显著,effects包生成的效应图却无交互?
广义线性混合模型交互效应图异常问题排查
我用R语言的lme4包给数据集拟合了广义线性混合模型,模型输出显示period与Adjunct存在显著交互作用(p<0.001)。之后我用effects包提取二者的效应,再用ggplot绘制交互效应图,但生成的图里看不到明显的交互趋势。怀疑是脚本有问题,相关数据集已备好。
提取效应脚本
var.adSem <- data.frame(Effect(c("period", "AdjunctSem"), m7)) head(var.adSem) var.adSem$period <- droplevels(var.adSem$period) levels(var.adSem$period) var.adSem$AdjunctSem <- droplevels(var.adSem$AdjunctSem) levels(var.adSem$AdjunctSem)
绘图脚本
perc <- function(x) {paste(100 * x, "%")} Plot1<-(ggplot(var.adSem,aes(x=factor(period, level=c('period_1', 'period_2','period_3')),fit, shape=AdjunctSem)) + geom_hline(yintercept=.5, linetype="dashed", alpha=.5) + geom_errorbar(aes(ymin=fit-se,ymax=fit+se),width=.2,position = position_dodge(0.3)) # + annotate("rect", xmin = c(4.5, 6.5), xmax = c(5.5, 9.5), # ymin = -Inf, ymax = Inf, # alpha = 0.2, fill = c("#6ac2ee")) + geom_point(size=4, position = position_dodge(0.3)) + labs(y="Probability of the ba-construction", x="period") + theme(#plot.title = element_text(size=20, face="bold", vjust=2), plot.title = element_blank(), axis.title.x = element_text(size=14, vjust=-0.5), axis.text.x = element_text(angle=90, hjust=1, vjust=0.5), axis.title.y = element_text(size=14, vjust=1.5), legend.position = "top") + scale_y_continuous(label=function(x){paste(100*x,"%")}, breaks=seq(0,1,.1), limits=c(0,1)))
可能的错误点及修正方案
- 变量名不匹配:模型交互项是
period和Adjunct,但提取效应时用的是AdjunctSem,需核对模型m7的公式,确保提取的变量与模型中的交互项一致。 - y轴映射缺失:ggplot的
aes中未明确指定y=fit,这会导致绘图逻辑错误,应修正为aes(x=..., y=fit, shape=AdjunctSem)。 - 缺少趋势折线:仅用散点和误差棒无法直观展示交互趋势,需添加
geom_line()并设置group=AdjunctSem和position=position_dodge(0.3),对齐散点与折线。 - 因子水平重复处理:提取效应后已用
droplevels()处理水平,绘图时无需重复用factor()指定,可改用scale_x_discrete()统一设置水平顺序。
修正后的绘图脚本示例
perc <- function(x) {paste(100 * x, "%")} Plot1 <- ggplot(var.adSem, aes(x = period, y = fit, shape = AdjunctSem, group = AdjunctSem)) + geom_hline(yintercept = .5, linetype = "dashed", alpha = .5) + geom_errorbar(aes(ymin = fit - se, ymax = fit + se), width = .2, position = position_dodge(0.3)) + geom_point(size = 4, position = position_dodge(0.3)) + geom_line(position = position_dodge(0.3)) + # 添加折线展示交互趋势 labs(y = "Probability of the ba-construction", x = "period") + theme(plot.title = element_blank(), axis.title.x = element_text(size = 14, vjust = -0.5), axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5), axis.title.y = element_text(size = 14, vjust = 1.5), legend.position = "top") + scale_y_continuous(label = perc, breaks = seq(0, 1, .1), limits = c(0, 1)) + scale_x_discrete(levels = c('period_1', 'period_2','period_3')) # 统一设置x轴水平顺序
内容的提问来源于stack exchange,提问作者nick.yili9393
相关产品推荐
相关产品推荐

