使用ggplot绘制lmer模型固定效应时遇报错求助
解决lmer模型固定效应绘图的错误问题
让我来帮你拆解这个错误的原因,然后给出针对性的解决方案:
错误根源分析
你遇到的核心问题是:Effect()函数生成的数据集里根本没有cut这个变量!
Effect()的作用是计算固定效应的边际预测值——它会把随机效应(这里的(1|cut))的影响边缘化(也就是用随机效应的均值0来计算预测),所以输出的data.frame(ee)里只包含你指定的固定效应变量(price、depth)和预测值fit,完全没有随机分组变量cut。
当你在ggplot里写color = cut时,R在当前数据集里找不到cut,就会去全局环境查找,结果找到了R内置的cut()函数(用来给连续变量分箱的工具函数),所以它把cut识别成了函数类型,自然就报出“无法自动为function类型的对象选择scale”的错误了。
解决方案分两种情况(匹配你的需求)
情况1:只想看固定效应的交互作用(忽略cut分组差异)
如果你的目标是展示price和depth这两个固定效应的交互关系,不需要区分不同cut的话,可以直接用Effect()的输出,按depth的水平来分组绘图:
library(ggplot2) library(lme4) library(lmerTest) library(effects) data(diamonds) # 拟合模型 m1 <- lmer(carat ~ price * depth + (1 | cut), diamonds) # 提取固定效应的边际效应 ee <- Effect(c("price", "depth"), m1) ee_df <- data.frame(ee) # 把depth转为因子,方便用离散颜色区分不同水平 ee_df$depth <- factor(ee_df$depth) # 绘图 ggplot(ee_df, aes(price, fit, color = depth)) + geom_line(linewidth = 1) + labs(title = "边际效应:价格与深度对钻石重量的影响", x = "价格", y = "预测重量(克拉)", color = "深度水平") + theme_minimal()
情况2:想按cut分组展示包含随机效应的预测曲线
如果你想看到不同cut分组下的预测差异(包含随机截距的影响),那Effect()就不适用了,得手动生成预测数据集,用predict()函数计算带随机效应的预测值:
library(ggplot2) library(lme4) library(lmerTest) data(diamonds) # 拟合模型 m1 <- lmer(carat ~ price * depth + (1 | cut), diamonds) # 生成预测数据集:包含price的序列、depth的代表性水平、所有cut分组 price_seq <- seq(min(diamonds$price), max(diamonds$price), length.out = 100) # 用depth的四分位数作为代表性水平,比均值±SD更贴合数据分布 depth_vals <- with(diamonds, quantile(depth, c(0.25, 0.5, 0.75))) pred_data <- expand.grid( price = price_seq, depth = depth_vals, cut = unique(diamonds$cut) ) # 计算包含随机效应的预测值(re.form = NULL表示保留所有随机效应) pred_data$fit <- predict(m1, newdata = pred_data, re.form = NULL) # 绘图:按cut分颜色,按depth分面展示交互效果 ggplot(pred_data, aes(price, fit, color = cut)) + geom_line(linewidth = 1) + facet_wrap(~depth, labeller = label_both) + labs(title = "不同切工下,价格与深度对钻石重量的预测", x = "价格", y = "预测重量(克拉)", color = "切工等级") + theme_minimal()
额外小贴士
- 用
predict()时,如果只想计算固定效应的预测值(忽略随机效应),把re.form设为~0就行。 Effect()输出里的depth是连续变量,直接用color = depth会生成连续色阶,转为因子后更适合展示不同水平的差异。
内容的提问来源于stack exchange,提问作者user974887
相关产品推荐
相关产品推荐

