R语言时间序列多元回归lm对象按输入顺序绘制残差图实现问询
解决方案
基础封装函数(无额外依赖)
该函数仅需传入lm对象即可生成按观测输入顺序排列的残差图,支持自定义传入时间向量作为X轴:
plot_residuals_in_order <- function(lm_obj, time_vec = NULL, add_reference = TRUE, ...) { # 提取模型残差 res <- residuals(lm_obj) # 确定X轴参数 if (is.null(time_vec)) { x <- seq_along(res) x_lab <- "观测输入顺序" } else { if (length(time_vec) != length(res)) stop("时间向量长度需与模型观测数一致") x <- time_vec x_lab <- "时间" } # 绘制散点图 plot(x, res, xlab = x_lab, ylab = "模型残差", main = "按顺序排列的残差分布图", pch = 16, col = "#2c3e50", ...) # 新增0值参考线 if (add_reference) abline(h = 0, col = "#e74c3c", lty = 2, lwd = 2) }
调用方式
- 仅生成按输入顺序排列的残差图:
plot_residuals_in_order(linearmodel) - 传入时间列生成时间-残差图:
plot_residuals_in_order(linearmodel, time_vec = data$date) - 支持传入基础绘图的自定义参数,比如修改点样式、标题:
plot_residuals_in_order(linearmodel, col = "darkgreen", pch = 2, main = "自定义残差图")
ggplot版本(适配Shiny美化需求)
如果需要更灵活的样式调整,也可以使用封装好的ggplot版本,直接返回ggplot对象:
library(ggplot2) plot_residuals_in_order_ggplot <- function(lm_obj, time_vec = NULL, add_reference = TRUE) { res <- residuals(lm_obj) plot_df <- data.frame( x = if (is.null(time_vec)) seq_along(res) else time_vec, residual = res ) x_lab <- if (is.null(time_vec)) "观测输入顺序" else "时间" p <- ggplot(plot_df, aes(x = x, y = residual)) + geom_point(color = "#2c3e50", size = 2, alpha = 0.8) + labs(x = x_lab, y = "模型残差", title = "按顺序排列的残差分布图") + theme_minimal() if (add_reference) { p <- p + geom_hline(yintercept = 0, color = "#e74c3c", linetype = "dashed", linewidth = 1) } return(p) }
调用后可以直接赋值给变量,完全符合你要求的形式:plot <- plot_residuals_in_order_ggplot(linearmodel)
Shiny 中使用示例
两种版本的函数都可以直接在Shiny中调用,以下是基础示例:
library(shiny) # 前端UI ui <- fluidPage( plotOutput("residual_plot") ) # 服务端逻辑 server <- function(input, output) { # 此处linearmodel为你提前构建好的lm对象,也可设置为reactive动态生成 output$residual_plot <- renderPlot({ plot_residuals_in_order(linearmodel) # 若使用ggplot版本直接调用函数即可,无需修改其他逻辑 }) } # 启动应用 shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者K.RAC
相关产品推荐
相关产品推荐

