如何使用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
相关产品推荐
相关产品推荐

