R中grid.arrange多图排布:自动设置y轴最优刻度范围
统一y轴刻度(最窄范围覆盖所有图形数据)
要让所有图形用最窄的统一y轴,关键是先把所有绘图数据里的置信区间上下限、预测值的极值找出来,然后把这个极值范围作为所有图形的y轴边界,既能保证所有数据都显示,又不会有多余留白。
具体实现代码(基于你的示例优化,支持批量处理):
library(fixest) library(marginaleffects) library(ggplot2) library(gridExtra) # 封装模型拟合+绘图数据提取的逻辑,批量处理更高效 get_plot_data <- function(model_formula) { mod <- feols(model_formula, data = mtcars) dat <- plot_slopes(mod, variables = "vs", condition = "am", draw = FALSE) dat$am <- as.numeric(as.character(dat$am)) return(dat) } # 定义所有需要拟合的模型公式(可无限扩展) formulas <- list( hp ~ vs * am | carb, hp ~ vs * am + mpg | carb ) # 批量生成所有绘图数据 plot_dats <- lapply(formulas, get_plot_data) # 计算全局y轴极值:取所有数据中conf.low的最小值、conf.high的最大值 global_y_min <- min(sapply(plot_dats, function(x) min(x$conf.low))) global_y_max <- max(sapply(plot_dats, function(x) max(x$conf.high))) # 批量生成带统一y轴的图形 create_unified_plot <- function(dat) { ggplot(dat, aes(x = am, y = estimate, ymin = conf.low, ymax = conf.high)) + geom_line() + geom_ribbon(alpha = .2) + theme_minimal() + labs(y = "Slopes") + # expand=0去掉默认留白,让刻度范围更紧凑;需要留白可改成c(0.05, 0) scale_y_continuous(limits = c(global_y_min, global_y_max), expand = c(0, 0)) } plots <- lapply(plot_dats, create_unified_plot) # 拼接并展示图形 grid.arrange(grobs = plots, ncol = 2)
单个图形使用独立最窄刻度
其实ggplot默认会自动调整y轴范围,把当前图形的所有数据(包括预测值和置信区间上下限)都包含进去,所以不手动设置limits的话,每个图形已经是最窄的自适应范围。
如果要手动明确控制(比如批量处理时确保逻辑一致),可以给每个图形单独计算自身的极值:
# 修改绘图函数,单独计算当前数据的y轴范围 create_independent_plot <- function(dat) { y_min <- min(dat$conf.low) y_max <- max(dat$conf.high) ggplot(dat, aes(x = am, y = estimate, ymin = conf.low, ymax = conf.high)) + geom_line() + geom_ribbon(alpha = .2) + theme_minimal() + labs(y = "Slopes") + scale_y_continuous(limits = c(y_min, y_max), expand = c(0, 0)) } # 批量生成独立刻度的图形 ind_plots <- lapply(plot_dats, create_independent_plot) # 拼接并展示图形 grid.arrange(grobs = ind_plots, ncol = 2)
批量处理大量图形的小技巧
- 把重复逻辑封装成函数,不管是10个还是100个模型,只要把公式加到
formulas列表里就行,无需重复写代码 - 若模型数量极多,可使用
purrr包的map系列函数替代lapply,语法更简洁 - 图形拼接可以试试
patchwork包,比gridExtra更灵活,支持自动排版、添加整体标题:library(patchwork) # 把所有图形拼接成2列布局 reduce(plots, `+`) + plot_layout(ncol = 2)
内容的提问来源于stack exchange,提问作者flâneur
相关产品推荐
相关产品推荐

