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

使用patchwork组合多个ggplot时,无法设置图例位置的问题

用Patchwork将ggplot图例定位到底行空白面板

问题场景

组合两个带分面的ggplot图形时,希望把图例放在底行facet 5的右侧、facet 3的下方空白区域,但尝试的代码未实现预期效果。

原始数据与绘图代码

library(tidyverse)
library(patchwork)
library(magrittr)

set.seed(123)

t1 <- expand_grid(
  rs = 1:2,
  fac = 1:5,
  grp = 1:2
) %>% 
  mutate(
    y = runif(20),
    row = fac %>% 
      is_in(1:3) %>%  
      ifelse(1, 2)
  )

# 上方3个分面的图(隐藏图例)
p1 <- t1 %>%
  filter(fac %>% is_in(1:3)) %>% 
  ggplot() +
  geom_point(
    aes(rs, y, color = factor(grp)),
    size = 3,
    position = position_dodge(width = .4)
  ) +
  facet_wrap(~fac, nrow = 1) +
  theme(legend.position = "none")

# 下方2个分面的图
p2 <- t1 %>%
  filter(fac %>% is_in(1:3) %>% not) %>% 
  ggplot() +
  geom_point(
    aes(rs, y, color = factor(grp)),
    size = 3,
    position = position_dodge(width = .4)
  ) +
  facet_wrap(~fac, nrow = 1)

无效尝试代码

p1 / p2 +
  plot_layout(
    design = "
    AAA
    BB#", 
    guides = "collect"
  ) &
  theme(
    legend.position = "inside",
    legend.position.inside = c(5/6, 1/4)
  )

解决方案

通过guide_area()专门预留图例位置,配合plot_layout的design参数指定图例放置区域,即可实现需求:

p1 / (p2 + guide_area()) +
  plot_layout(
    design = "
    AAA
    BBL",
    guides = "collect"
  ) &
  theme(
    legend.position = "center" # 可根据需求修改为left/right/top/bottom
  )

说明

  1. guide_area():为图例创建专属面板,放在p2的右侧
  2. plot_layout(design = "AAA\nBBL"):定义布局结构——上行3个绘图面板(A),底行2个绘图面板(B)+1个图例面板(L)
  3. guides = "collect":合并两个图的图例,避免重复显示
  4. theme(legend.position = "center"):调整图例在其专属面板内的对齐方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:52:39