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

R语言排列多幅ggplot绘图时如何保持各图x轴标签与对应轴对齐

这个需求可以实现,两种常用方案如下:

方案1:继续使用patchwork包

出现对齐问题的核心原因是patchwork默认同时对齐水平、垂直方向的绘图面板边缘,p1的垂直x轴文本撑大了底部空间,导致p2的底部被同步下拉。仅需修改对齐规则,保留水平对齐、关闭垂直对齐即可:

library(ggplot2)
library(patchwork)

# 示例数据
mtcars2 <- mtcars[1:5, ]
mtcars2$mod <- row.names(mtcars2)

# 绘制两张图
p1 <- ggplot(mtcars2, aes(mod, mpg)) +
  geom_col() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0, hjust = 1))

p2 <- ggplot(mtcars2, aes(hp, disp)) +
  geom_point()

# 排列时仅水平对齐,关闭垂直对齐
p1 + p2 + plot_layout(align = "h")

方案2:使用cowplot包

cowplot的plot_grid函数默认对齐逻辑更适配该场景,不会强制拉伸图的尺寸:

library(ggplot2)
library(cowplot)

# 同上先绘制p1、p2
mtcars2 <- mtcars[1:5, ]
mtcars2$mod <- row.names(mtcars2)

p1 <- ggplot(mtcars2, aes(mod, mpg)) +
  geom_col() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0, hjust = 1))

p2 <- ggplot(mtcars2, aes(hp, disp)) +
  geom_point()

# 排列绘图
plot_grid(p1, p2, nrow = 1, align = "h")

如果需要更精细的边距调整,还可以为单个图添加theme(plot.margin = margin(t=5, r=5, b=5, l=5, unit = "pt"))单独调整上下左右的边距,满足个性化排版需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:24:03