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

如何对齐两个ggpubr直方图使其相向展示,解决cowplot对齐失效问题

实现相向对齐直方图的正确方案

你之前的代码问题在于直接将两个直方图叠放在同一画布区域,而非按上下分区拼接,且未统一x轴范围,导致无法对齐。可按以下步骤实现:

前置处理(两种方案通用)

ggpubr生成的直方图本质是ggplot2对象,可直接用ggplot2语法调整:

  1. 统一两个图的x轴范围,这是x轴刻度对齐的核心
  2. 对上方展示的直方图做y轴反转,同时移除其x轴刻度、标签、标题,让两个图共用底部x轴
  3. 调整两个图的上下边距,缩小中间空隙

方案1:使用patchwork包实现(更简单)

library(ggplot2)
library(patchwork)

# 1. 处理上方朝下的直方图
Symhist_rev <- Symhist +
  scale_y_reverse() + # 反转y轴,柱子向下生长
  theme(
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    plot.margin = margin(b = 0) # 移除底部边距
  )

# 2. 处理下方正常的直方图
Asyhist_norm <- Asyhist +
  theme(
    plot.margin = margin(t = 0) # 移除顶部边距
  )

# 3. 统一x轴范围
x_min <- min(layer_scales(Symhist)$x$range$range, layer_scales(Asyhist)$x$range$range)
x_max <- max(layer_scales(Symhist)$x$range$range, layer_scales(Asyhist)$x$range$range)
Symhist_rev <- Symhist_rev + xlim(x_min, x_max)
Asyhist_norm <- Asyhist_norm + xlim(x_min, x_max)

# 可选:统一y轴最大值让上下更对称
y_max <- max(layer_scales(Symhist)$y$range$range, layer_scales(Asyhist)$y$range$range)
Symhist_rev <- Symhist_rev + ylim(y_max, 0) # 反转后上限在前
Asyhist_norm <- Asyhist_norm + ylim(0, y_max)

# 4. 垂直拼接
final_plot <- Symhist_rev / Asyhist_norm
final_plot

方案2:使用cowplot包实现

library(cowplot)

# 前置处理和方案1完全一致,先得到Symhist_rev和Asyhist_norm两个对象

# 对齐两个图的纵轴
aligned_plots <- align_plots(Symhist_rev, Asyhist_norm, align = "v", axis = "lr")

# 按上下布局拼接
final_plot <- plot_grid(
  aligned_plots[[1]], 
  aligned_plots[[2]], 
  ncol = 1, 
  rel_heights = c(1, 1) # 可调整两个图的高度占比
)
final_plot

内容的提问来源于stack exchange,提问作者Paolo Vallejo Janeta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:24:04