使用ggplot2绘制残差图时遇.fitted对象未找到错误的求助
问题:ggplot2绘制残差图提示.fitted对象未找到
我正在尝试通过残差分析可视化数据,判断其是否服从正态分布。用R内置功能绘制残差图很简单,但我更偏好使用ggplot2,不过持续遇到对象找不到的问题,最近的错误是提示.fitted对象未找到。
我的代码:
library(readxl) library(ggplot2) ggplot(Data_proj, aes(x = x1/1000, y = as.numeric(y))) + geom_point() + geom_smooth(method = "lm") + facet_wrap(~x2) ggplot(Data_proj, aes(x = .fitted, .resid)) + geom_point() + geom_hline(yintercept = 0)
错误信息:
Error in `geom_point()`: ! Problem while computing aesthetics. ℹ Error occurred in the 1st layer. Caused by error in `FUN()`: ! object '.fitted' not found Run `rlang::last_trace()` to see where the error occurred.
补充数据:
data <- tibble::tibble( x1 = c(8135, 1629, 2824, 9780, 8856, 10387), x2 = c(1, 1, 1, 0, 1, 1), y = c("92.1281", "52.3726", "49.3202", "195.8212", "100.8019", "113.7111"), .fitted = c( `1` = 128.689193244635, `2` = 45.2529218882561, `3` = 60.5782130457833, `4` = 149.785514545164, `5` = 137.935665984866, `6` = 157.569992982502 ), .resid = c( `1` = -36.5610932446345, `2` = 7.11967811174389, `3` = -11.2580130457833, `4` = 46.0356854548364, `5` = -37.1337659848664, `6` = -43.8588929825017 ), )
解决方案
错误原因
geom_smooth(method="lm")仅在图中绘制拟合直线,不会将拟合值(.fitted)和残差(.resid)存入原始数据集Data_proj,直接调用这两个变量自然会找不到。- 补充的数据集命名为
data,但ggplot代码中调用的是Data_proj,数据集名称不匹配,也会导致列找不到。
修复步骤
方法1:手动拟合模型并合并结果到数据集
先拟合线性模型,提取拟合值和残差,合并到原始数据集后再绘图:
library(readxl) library(ggplot2) # 处理数据:将y转换为数值型 Data_proj$y_num <- as.numeric(Data_proj$y) # 拟合包含x1和x2的线性模型(对应补充数据中的.fitted计算逻辑) model <- lm(y_num ~ x1 + x2, data = Data_proj) # 将拟合值和残差合并到原数据集 Data_proj <- cbind(Data_proj, .fitted = fitted(model), .resid = residuals(model)) # 绘制残差图 ggplot(Data_proj, aes(x = .fitted, y = .resid)) + geom_point() + geom_hline(yintercept = 0, linetype = "dashed", color = "red")
方法2:直接使用补充的数据集
注意数据集名称要匹配,将ggplot中的Data_proj改为data即可:
ggplot(data, aes(x = .fitted, y = .resid)) + geom_point() + geom_hline(yintercept = 0, linetype = "dashed", color = "red")
方法3:用broom包简化模型结果整理
broom包可以快速将模型结果转换为包含拟合值、残差的tidy数据框,更方便绘图:
library(readxl) library(ggplot2) library(broom) # 处理数据并拟合模型 Data_proj$y_num <- as.numeric(Data_proj$y) model <- lm(y_num ~ x1 + x2, data = Data_proj) # 用augment生成包含拟合值、残差的数据框 model_aug <- augment(model) # 绘制残差图 ggplot(model_aug, aes(x = .fitted, y = .resid)) + geom_point() + geom_hline(yintercept = 0)
内容的提问来源于stack exchange,提问作者Razrer
相关产品推荐
相关产品推荐

