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

如何在patchwork拼接的ggplot中仅保留单个图例?

解决Patchwork拼接图重复图例的问题

你可以通过Patchwork的图例收集功能统一管理重复图例,以下是两种实用实现方式:

方法一:先隐藏子图图例,再统一收集

先让每个子图不显示图例,再通过plot_layout(guides = "collect")合并展示单个图例,同时可指定图例位置:

library(tidyverse)
library(patchwork)

mtboxes <- mtcars |> 
  select(-cyl) |> 
  imap(~ ggplot() +
        geom_boxplot(aes(y = .x, fill = factor(mtcars$cyl))) +
        labs(title = .y, x = NULL, y = NULL) +
        theme(legend.position = "none")) # 隐藏每个子图的图例

mtboxes <- mtboxes |> Reduce(`+`, x = _)

# 收集图例并设置位置(可选top/right/bottom)
mtboxes + plot_layout(guides = "collect") & theme(legend.position = "top")

方法二:直接自动合并重复图例

无需提前隐藏子图图例,Patchwork会自动识别重复的图例规则并合并,仅保留一个:

library(tidyverse)
library(patchwork)

mtboxes <- mtcars |> 
  select(-cyl) |> 
  imap(~ ggplot() +
        geom_boxplot(aes(y = .x, fill = factor(mtcars$cyl))) +
        labs(title = .y, x = NULL, y = NULL))

mtboxes <- mtboxes |> Reduce(`+`, x = _)

# 自动合并图例并设置位置为底部
mtboxes + plot_layout(guides = "collect") & theme(legend.position = "bottom")

额外优化

如果需要修改图例标题,只需在任意一个子图中设置labs(fill = "气缸数"),收集后的图例就会统一使用这个标题,无需在所有子图中重复配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:27:07