Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Only collect partial of legends with patchwork

I am trying to only "collect" partial of legends with patchwork, below is a minimal example.

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")
p3 <- ggplot(mtcars, aes(mpg, qsec, color = wt)) + geom_point()


(p1 | p2)/(p3 | p3 | p3) + patchwork::plot_layout(guides="collect") & theme(legend.position = "bottom")

The expectation is to keep the legend of p2 still at the bottom of p2, and collect and position the rest of legends at the bottom.

Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option would be to wrap p2 in wrap_elements where I additionally removed the plot.margin around p2 to still align the plot with the other plots:

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")
p3 <- ggplot(mtcars, aes(mpg, qsec, color = wt)) +
  geom_point()


(p1 | wrap_elements(
  p2 + theme(plot.margin = margin())
)) / (p3 | p3 | p3) +
  patchwork::plot_layout(guides = "collect") &
  theme(legend.position = "bottom")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading