R语言:如何快速将模型对象plot(mod)生成的4幅图合并为2×2面板图?
Hey there! Let's break down why your par(mfrow=c(2,2)) setup isn't playing nice with plot(mod) and get those diagnostic plots into a 2×2 grid quickly.
First, a quick reality check: the default plot.lm() function (and plot.aov(), since aov objects are just specialized lm objects) already creates a 2×2 panel of diagnostic plots by default. The issue you're facing is almost certainly the ask parameter, which is enabled automatically in interactive environments like RStudio or RGui.
When ask=TRUE (the default), R will prompt you to press Enter between each plot. This means each diagnostic chart takes over the entire plotting device, ignoring your mfrow setting entirely.
Quick Fix 1: Disable Interactive Prompt
The simplest solution is to turn off the ask parameter directly in your plot() call. This will render all 4 plots in a 2×2 grid in one go, no extra par() setup needed:
# Fit your model (example with mtcars dataset) mod <- lm(mpg ~ wt + hp, data = mtcars) # Generate 2×2 diagnostic panel instantly plot(mod, ask = FALSE)
Quick Fix 2: Manual Grid Control
If you want more flexibility (like mixing diagnostic plots with other visuals, or selecting specific charts), set up your grid first and plot each diagnostic chart individually using the which argument:
# Define 2×2 plotting grid par(mfrow = c(2,2)) # Plot each diagnostic chart one by one plot(mod, which = 1) # Residuals vs Fitted Values plot(mod, which = 2) # Normal Q-Q Plot plot(mod, which = 3) # Scale-Location Plot plot(mod, which = 4) # Residuals vs Leverage
This works because we're explicitly placing each plot into the pre-defined grid, bypassing the interactive prompt that was overriding your layout.
To recap: Your original two lines failed because the default ask=TRUE setting resets the plotting device for each individual plot, wiping out your mfrow configuration. Disabling ask or plotting each chart manually fixes this.
内容的提问来源于stack exchange,提问作者hmnoidk

