R中plot_model绘制GLM交互图如何正确显示原始数据点
R中plot_model绘制三向交互图叠加原始点时末图异常解决方案
问题场景
- 基于鸟类维基百科页面浏览量与生活史特征的关联分析需求,构建GLM模型后用
plot_model绘制交互效应图,初始代码可正常出图:
m2.0_human_sedentary = glm(log_av_total_views ~ log_life_s * human_sett * log_weight_u_m + sedentary, data = model_totalcount_lifeh) plot_model(m2.0_human_sedentary, type = "int")
- 默认输出的图表不展示单个原始数据点,为直观呈现数据实际分布,添加
show.data = TRUE参数尝试叠加原始点:
plot_model(m2.0_human_sedentary, type = "int", show.data = TRUE)
- 代码运行全程无报错,输出的4张子图中有3张可正常显示叠加的数据点,但最后一张三向交互子图完全不具备正常图表形态。
- 用到的示例数据结构如下(暂未放入模型调用的全字段,需要可随时补充):
model_totalcount_lifeh <- structure( list( title = c( "Peregrine falcon", "Golden eagle", "Osprey", "Common raven", "Mallard" ), category.x = structure( c(1L, 1L, 1L, 1L, 1L), levels = c("LC", "NT", "VU"), class = "factor" ), av_total_views = c( 69717.4912280702, 53478.4210526316, 49867.9473684211, 39600.8245614035, 33459.8771929825 ), av_summer_views = c( 78226.962962963, 54020.7777777778, 58687.5925925926, 46819.7037037037, 36948.7777777778 ), Wing = c(332.5, 626, 482, 421.4, 272), life_s = c(17, 32, 27, 23, 23) ), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,-5L), groups = structure( list( title = c( "Common raven", "Golden eagle", "Mallard", "Osprey", "Peregrine falcon" ), .rows = structure( list(4L, 2L, 5L, 3L, 1L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list") ) ), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,-5L), .drop = TRUE ) )
故障原因
这是plot_model对分组tibble(grouped_df类对象)的兼容性bug:绘制三向交互子图叠加原始点时,函数没有自动清除数据集的分组属性,导致原始点的坐标映射逻辑错位,最终出图形态异常,且该逻辑问题不会触发运行报错。
修复方法
任选一种即可解决问题:
- 最稳妥方案:建模前先取消数据集的分组属性,从根源避免属性干扰,之后重新拟合模型再绘图即可
# 清除数据的分组属性 model_totalcount_lifeh <- ungroup(model_totalcount_lifeh) # 重新拟合模型 m2.0_human_sedentary = glm(log_av_total_views ~ log_life_s * human_sett * log_weight_u_m + sedentary, data = model_totalcount_lifeh) # 重新绘图 plot_model(m2.0_human_sedentary, type = "int", show.data = TRUE)
- 无需重跑模型的方案:绘图时手动传入转为普通数据框的原始数据,绕开函数的分组识别bug
plot_model(m2.0_human_sedentary, type = "int", show.data = TRUE, dot.alpha = 0.6, # 可选:调整原始点透明度,避免遮挡拟合线 jitter = 0.2, # 可选:给点加少量横向扰动,避免点完全重叠 data = as.data.frame(model_totalcount_lifeh))
内容的提问来源于stack exchange,提问作者Olwen Belgrove
相关产品推荐
相关产品推荐

