如何针对数据框中特定日期绘制线性模型残差图?
Fixing Your
plot_one_day Function for Daily Residual Plots Let's walk through refining your function to reliably plot model residuals for a specific date, without relying on dplyr. First, let's break down why the original approach had issues, then jump to the corrected code.
What Was Tripping Up the Original Code?
- Your initial plot attempt compared a character string (from
substr(MyData$Time,1,10)) to a POSIXct date object—R can't properly match these types, leading to incorrect filtering or errors. - The first version of your
plot_one_dayfunction used character-string dates to filter a POSIXctTimecolumn, which works unpredictably. It also pulled the title from the first row of filtered data, which would fail if no data matched the date.
Corrected plot_one_day Function
Here's the robust, dplyr-free version:
plot_one_day <- function(LM, Day, DF) { # Attach residuals to the original data frame (aligns perfectly with na.exclude) DF$Residuals <- resid(LM) # Create proper POSIXct start/end times for the target day day_start <- as.POSIXct(paste(Day, "00:00:00"), format = "%Y-%m-%d %H:%M:%S") day_end <- as.POSIXct(paste(Day, "23:59:59"), format = "%Y-%m-%d %H:%M:%S") # Filter to the target day, removing rows with NA residuals filtered_data <- DF[DF$Time >= day_start & DF$Time <= day_end & !is.na(DF$Residuals), ] # Handle empty data to avoid plot errors if (nrow(filtered_data) == 0) { message(paste("Oops, no data available for", Day)) return(invisible(NULL)) } # Build the plot plot(Residuals ~ Time, data = filtered_data, main = paste("Residuals for", Day), xlab = "Time of Day", ylab = "Model Residuals", xlim = c(day_start, day_end), ylim = range(filtered_data$Residuals), col = "darkslateblue", pch = 16) # Add a clear reference line at y=0 abline(h = 0, col = "firebrick", lwd = 2) # Optional: Format x-axis to show hours (easier to read than full timestamps) axis.POSIXct(1, at = seq(day_start, day_end, by = "2 hours"), format = "%H:%M") }
What Makes This Better?
- Type-safe filtering: We convert the input
Daystring to POSIXct times, so comparisons with yourTimecolumn (also POSIXct) are 100% reliable. - Residual alignment: Since you used
na.action = na.excludein your model,resid(LM)includes NA values for excluded rows—directly attaching it toDFensures every residual lines up with its original row. - Error protection: The function checks if filtered data is empty and sends a friendly message instead of crashing.
- Cleaner visualization: Added a y-axis label, formatted the x-axis to show hours, and tweaked colors/markers for readability.
Test It Out
Call the function exactly as you intended:
plot_one_day(LM_1, "2015-05-07", MyData)
You'll get a clear plot of residuals for the specified day, with the red line at y=0 making it easy to spot positive vs. negative residuals.
内容的提问来源于stack exchange,提问作者Saalva
相关产品推荐
相关产品推荐

