ggplot2批量绘图时自动在图左上角放置线性回归结果的技术需求
Got it, let's fix this for you! The problem with your current approach is that it locks the regression statistics into the plot title, which means you can't set a separate, meaningful title for your visualization. Instead, we can use ggplot's annotate() function to place the adjusted R² and p-value directly in the top-left corner of the plot, leaving the title field free for your custom text.
Here's the updated, reusable function:
ggplotRegression <- function(fit) { require(ggplot2) # Pull the x and y variable names from the fitted model x_var <- names(fit$model)[2] y_var <- names(fit$model)[1] # Calculate and format the regression stats adj_r2 <- signif(summary(fit)$adj.r.squared, 2) p_val <- signif(summary(fit)$coef[2, 4], 2) stats_label <- paste0("Adj R² = ", adj_r2, "\nP = ", p_val) # Build the base plot with stats annotation ggplot(fit$model, aes_string(x = x_var, y = y_var)) + geom_point() + stat_smooth(method = "lm", color = "red") + # Place stats in top-left corner, aligned to the edge annotate("text", x = min(fit$model[[x_var]]), y = max(fit$model[[y_var]]), label = stats_label, hjust = 0, vjust = 1, size = 4, color = "black") + theme_bw() # Base theme included, but you can override later }
Key Improvements:
- Stats in Top-Left: Uses
annotate()to position the R² and p-value at the top-left of the plot, based on the actual data ranges (so it won't drift off-screen no matter your variables). - Custom Title Support: The title field is now free—you can add a meaningful, variable-specific title whenever you want.
- Flexible Formatting: Adjust the
signif()argument (currently set to 2) if you want more/less decimal places for your stats. - Reusable: Works with any linear model fit from
lm()—just pass the model object, and it handles the rest.
Example Usage with mtcars:
Let's test it with your 4-cylinder mtcars subset, adding a custom title and your preferred point styling:
# Load dplyr for filtering (if not already loaded) require(dplyr) # Filter 4-cylinder cars disp_vs_wt_cyl4 <- mtcars %>% filter(cyl == 4) # Fit the linear model fit <- lm(disp ~ wt, data = disp_vs_wt_cyl4) # Generate the plot with stats, custom title, and point style ggplotRegression(fit) + geom_point(size = 3.74, colour = "#0c4c8a") + labs(title = "Displacement vs. Vehicle Weight (4-Cylinder Cars)")
This will give you a clean plot with the regression line, your styled points, a custom title, and the regression stats neatly tucked in the top-left corner—perfect for comparing any pair of variables in your dataset.
内容的提问来源于stack exchange,提问作者Tiptop

