You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中居中对齐最后三个facet分面?

解决ggplot2分面最后一行居中的问题

方法1:使用ggh4x的facet_wrap2(推荐,简单高效)

ggh4x是ggplot2的扩展包,专门优化了分面布局,支持让最后一行的分面自动居中。

  • 安装并加载包:
install.packages("ggh4x")
library(ggh4x)
  • 修改原代码替换分面函数:
library(ggplot2)
library(ggh4x)

ggplot(df, aes(x = pos, y = mean_ratio_f)) +
  geom_smooth(aes(group = factor(size)), method = "lm", se = FALSE, linewidth = 0.5) +
  # 用facet_wrap2替代facet_wrap,指定列数并开启居中对齐
  facet_wrap2(. ~ size, scales = 'free_x', ncol = 4, align = "center") +
  labs(x = "X", y = "Y")

这里ncol=4可根据需求调整(比如设为5列,最后一行3个分面仍会居中),align="center"会自动让最后一行的分面在整体宽度上居中。

方法2:用patchwork手动组合布局(无需额外扩展包也可实现)

如果不想安装新包,可通过patchwork将分面拆成两部分,手动让底部的3个分面居中:

  • 安装并加载包:
install.packages("patchwork")
library(patchwork)
  • 拆分数据并组合图形:
library(ggplot2)
library(patchwork)
library(dplyr) # 用于数据筛选

# 拆分数据为前20组和最后3组
df_upper <- df %>% filter(size %in% 3:22)
df_lower <- df %>% filter(size %in% 23:25)

# 绘制顶部4列5行的分面图
p_upper <- ggplot(df_upper, aes(x = pos, y = mean_ratio_f)) +
  geom_smooth(aes(group = factor(size)), method = "lm", se = FALSE, linewidth = 0.5) +
  facet_wrap(. ~ size, scales = 'free_x', ncol = 4) +
  labs(x = "X", y = "Y") +
  theme(plot.margin = margin(5, 5, 5, 5))

# 绘制底部3列的分面图
p_lower <- ggplot(df_lower, aes(x = pos, y = mean_ratio_f)) +
  geom_smooth(aes(group = factor(size)), method = "lm", se = FALSE, linewidth = 0.5) +
  facet_wrap(. ~ size, scales = 'free_x', ncol = 3) +
  labs(x = "X", y = "Y") +
  theme(plot.margin = margin(5, 5, 5, 5))

# 组合图形,用空白占位让底部图居中
p_upper / (plot_spacer() + p_lower + plot_spacer()) +
  plot_layout(heights = c(5, 1), widths = c(1, 3, 1))

通过左右添加空白占位图,让底部的3个分面在整体宽度上居中,heights和widths参数可调整上下部分的比例和空白宽度。


内容的提问来源于stack exchange,提问作者Chris Ruehlemann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:05:23