You need to enable JavaScript to run this app. 如何用R的cowplot或其他库垂直对齐两个ggplot绘图
优惠活动
大模型
产品
解决方案
定价
更多

如何用R的cowplot或其他库垂直对齐两个ggplot绘图

对齐失效原因

cowplot的plot_grid()函数的align参数基于笛卡尔坐标系的轴边界逻辑实现对齐,你绘制的p1使用了coord_polar()极坐标转换,破坏了常规的轴边界识别规则,所以align='v'参数无法生效。


解决方案1:使用patchwork包(推荐)

patchwork包对特殊坐标系的适配性更好,不需要额外复杂操作即可实现对齐,示例代码如下:

# 加载依赖包
library(patchwork)
library(ggplot2)
library(dplyr)

# 原有数据处理与绘图代码
manufac_count <-  mpg %>%
  count(manufacturer) %>% 
  mutate(ymax = cumsum(n),
         ymin = lag(ymax, n = 1, default = 0))

model_count <- mpg %>%
  group_by(manufacturer) %>%
  count(model) %>%
  ungroup() %>% 
  mutate(ymax = cumsum(n),
         ymin = lag(ymax, n = 1, default = 0))

p1 <- ggplot(manufac_count) +
  geom_rect(aes(xmin = 2,
                xmax = 3,
                ymin = ymin,
                ymax = ymax,
                fill = manufacturer),
            color = 'white') +
  geom_rect(data = model_count,
            aes(xmin = 3,
                xmax = 4,
                ymin = ymin,
                ymax = ymax,
                fill = model),
            color = 'white',
            show.legend = FALSE) +
  xlim(0 , 4) +
  coord_polar(theta = 'y' ) +
  theme(legend.position = 'none',
        # 统一两个图的边距可实现更精准的对齐
        plot.margin = unit(c(0.5,0.5,0.5,0.5), "lines"))

p2 <- ggplot(data = mpg,
             mapping =  aes(x = hwy)) +
  geom_histogram(binwidth = 3) +
  theme(plot.margin = unit(c(0.5,0.5,0.5,0.5), "lines"))

# 垂直拼接自动对齐
p1 / p2

解决方案2:基于cowplot手动对齐grob

如果需要继续使用cowplot,可以将绘图转为grob对象后手动统一宽度再拼接:

library(cowplot)
library(grid)

# 将ggplot对象转为grob对象
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)

# 统一两个grob的宽度
max_width <- unit.pmax(g1$widths, g2$widths)
g1$widths <- max_width
g2$widths <- max_width

# 拼接输出
plot_grid(g1, g2, nrow = 2)

内容的提问来源于stack exchange,提问作者Claudio Carrasco Hormazábal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 18:57:03