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

如何使用patchwork仅收集部分图例并保留指定子图图例位置

Solution

To keep p2's legend at its own bottom while collecting the rest of the legends at the overall bottom, you can use patchwork::guide_collect(FALSE) on p2 to exclude its legend from the global collection. Here's the modified code:

library(patchwork)
library(ggplot2)

p1 <- ggplot(mtcars, aes(mpg, disp, color = factor(vs))) + geom_point()
p2 <- ggplot(mtcars, aes(mpg, hp, color = factor(cyl))) + 
  geom_point() + 
  theme(legend.position = "bottom") +
  guides(color = patchwork::guide_collect(FALSE)) # Exclude this legend from collection
p3 <- ggplot(mtcars, aes(mpg, qsec, color = wt)) + geom_point()

# Combine plots with guide collection
(p1 | p2)/(p3 | p3 | p3) + 
  patchwork::plot_layout(guides = "collect") & 
  theme(legend.position = "bottom")

Explanation

  • Adding guides(color = patchwork::guide_collect(FALSE)) to p2 tells patchwork not to collect this specific legend, so it stays anchored to p2's bottom.
  • The global plot_layout(guides = "collect") still gathers legends from p1 and p3, placing them at the overall bottom of the combined plot.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:42:45