如何强制Rmarkdown中GLM诊断图显示为正方形?
Ah, I’ve run into this exact issue before—getting publication-ready square diagnostic plots from glm.diag.plots in R Markdown can feel tricky when you can’t drag to resize like in RStudio. The first thing to clarify: glm.diag.plots uses R’s base graphics system, not ggplot2, so digging through ggplot documentation won’t yield solutions here. We need to work with base graphics parameters instead.
Here are two reliable methods to force square plots that look great in your document:
1. Use par(pin = ...) to set per-plot square dimensions
The pin parameter in par() lets you explicitly set the width and height of each plotting region (in inches). Setting them to equal values ensures a square shape. Wrap your plot code in a block where you first set this parameter:
library(MASS) # Fit a sample GLM model (replace with your own model) model <- glm(mpg ~ wt + hp, data = mtcars, family = gaussian) # Force each diagnostic plot to be a 4x4 inch square par(pin = c(4, 4)) # Tweak the numeric values to adjust size glm.diag.plots(model)
2. Combine with R Markdown chunk options for polished output
For more control over the final rendered size in your document, pair par() with chunk options like fig.width and fig.height. Since glm.diag.plots defaults to a 2x2 grid of plots, set the chunk’s overall dimensions to twice your per-plot size:
First, the code inside the chunk:
library(MASS) model <- glm(mpg ~ wt + hp, data = mtcars, family = gaussian) # Configure a 2x2 grid with 3x3 inch square subplots par(mfrow = c(2, 2), pin = c(3, 3)) glm.diag.plots(model)
Then set your chunk options to match the total grid size:
{r glm-diagnostic-plots, fig.width=6, fig.height=6}
This ensures the entire 2x2 grid fits into a 6x6 inch square, with each individual diagnostic plot being a perfect 3x3 inch square—ideal for publication standards.
Why this works
Unlike ggplot2, which uses its own layout system, base graphics relies on the par() function to configure plot dimensions, margins, and layout. By setting pin to equal width and height, you lock each plotting region into a square shape, overriding the default rectangular settings.
内容的提问来源于stack exchange,提问作者TheProletariat

