Myriad
Myriad

Reputation: 351

specify specific position for collected legend in patchwork

I am using the patchwork package in r to create panels of plots like:

panel<- (p1+  plot_spacer()+p2 + p3)+
    plot_layout(ncol = 2) +
  plot_layout(guides = "collect")
panel

enter image description here

I want to specify the legend to go to the empty top-right panel, more or less like this enter image description here

Appreciate any pointers

Upvotes: 2

Views: 2284

Answers (2)

stefan
stefan

Reputation: 124213

For this use case patchwork provides guide_area() which could be used to place the legend:

library(patchwork)
library(ggplot2)

p1 <- p2 <- p3 <- ggplot(mtcars, aes(hp, mpg, color = factor(cyl))) +
  geom_point()

p1 + guide_area() + p2 + p3 +
  plot_layout(ncol = 2) +
  plot_layout(guides = "collect")

Upvotes: 4

Myriad
Myriad

Reputation: 351

as suggested by @kat, one solution is to use cowplot in combination to patchwork

library("cowplot")
library("patchwork")
 
legend_grob <-cowplot::get_legend(p1) #get legend

#emove legend in the original plots
p1 <- p1+theme(legend.position = "none")
p2 <- p2+theme(legend.position = "none")
p3 <- p3+theme(legend.position = "none")

# now patchwork it
p1+legend_grob+p2+p3)
    plot_layout(ncol = 2)

enter image description here

Upvotes: 1

Related Questions