如何用R的plm包绘制双向固定效应模型的残差vs拟合值图
问题描述
我使用plm包估计了双向(个体和时间固定效应)固定效应模型,回归代码为:
my_plm_model <- plm(Y ~ X, data = my_data, model = "within", effect = "twoways")
为验证线性模型是否适配我的数据,我想要绘制残差vs拟合值图,但使用命令:
plot(fitted(my_plm_model), res)
时出现错误:
Error in match.arg(plot) :
'arg' must be NULL or a character vector
而用lm模型执行该命令可正常绘图,推测问题源于该命令不兼容plm回归。请问如何解决此绘图问题?若无解决办法,还有哪些方式可检验回归的线性假设?
解决方案
一、修复残差vs拟合值绘图问题
plm对象的残差、拟合值提取逻辑与lm不同,直接调用plot()会触发方法冲突,可按以下步骤操作:
- 正确提取拟合值与残差
使用plm包的专用提取函数,并指定type = "response"确保结果为原始尺度(而非去均值后的结果):
fit_vals <- fitted(my_plm_model, type = "response") res_vals <- residuals(my_plm_model, type = "response")
- 绘制残差图
- 基础R绘图:
plot(fit_vals, res_vals, xlab = "拟合值", ylab = "残差", main = "残差vs拟合值") abline(h = 0, col = "red", lwd = 2) # 添加水平参考线 - ggplot2绘图(更美观且可定制):
library(ggplot2) ggplot(data.frame(fit = fit_vals, res = res_vals), aes(x = fit, y = res)) + geom_point(alpha = 0.6) + geom_hline(yintercept = 0, color = "red", linewidth = 1) + labs(x = "拟合值", y = "残差", title = "残差vs拟合值") + theme_minimal()
二、其他检验线性假设的方法
如果绘图方式仍有问题,可通过以下统计方法验证线性假设:
- 成分残差图(偏残差图):使用
car包的crPlots()函数,直观查看自变量与调整后残差的关系,若存在非线性会呈现明显曲线趋势:library(car) crPlots(my_plm_model) - Box-Tidwell检验:直接检验自变量与因变量的线性关系,原假设为线性成立,若p值小于显著性水平(如0.05)则拒绝线性假设:
boxTidwell(Y ~ X, data = my_data) - 拟合不足检验:将自变量分组,通过ANOVA检验组内均值与线性拟合值的差异,若差异显著则说明线性模型拟合不足。
- 非参数回归对比:用核回归等非参数方法拟合数据,对比线性拟合曲线与非参数拟合曲线的差异,若差距明显则线性假设不成立:
library(ggplot2) library(np) # 拟合非参数模型 np_fit <- npreg(Y ~ X, data = my_data) # 绘制对比图 ggplot(my_data, aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_line(aes(y = fitted(my_plm_model)), color = "blue", linewidth = 1) + geom_line(aes(y = fitted(np_fit)), color = "red", linewidth = 1, linetype = "dashed") + labs(title = "线性拟合vs非参数拟合对比") + theme_minimal()
内容的提问来源于stack exchange,提问作者Muller I.
相关产品推荐
相关产品推荐

