collecting guides in patchwork not working for two grid faceted ggplots

Viewed 429

I'm trying to add two ggplots that have used facet_grid together and collect the guides for the colouring underneath. It seems to only be collecting the guide from the second plot and even when I try to turn off the guide in the first plot it is still shown as a duplicate

Managed to replicate the error here enter image description here

with this code

library(tidyverse)
library(patchwork)
n <- 100
data <- data.frame(
  plot_label = c(rep("A", n), rep("B", n)),
  facet_x = sample(c("p", "q", "r"), 2*n, replace = TRUE),
  facet_y = sample(1:5, 2*n, replace = TRUE),
  colour = sample(c("x", "y", "z"), 2*n, replace = TRUE),
  random_x = runif(2*n),
  random_y = rnorm(2*n)
)

p1 <- data %>%
  filter(plot_label == "A") %>%
  ggplot(aes(x = random_x, y = random_y)) +
  geom_point(aes(colour = colour)) +
  scale_colour_manual(values = c("purple", "skyblue", "green"), name = "myscale") +
  facet_grid(facet_x~facet_y)
p2 <- data %>%
  filter(plot_label == "B") %>%
  ggplot(aes(x = random_x, y = random_y)) +
  geom_point(aes(colour = colour)) +
  scale_colour_manual(values = c("purple", "skyblue", "green"), name = "myscale") +
  facet_grid(facet_x~facet_y)
plot <- (p1 + p2) &
  plot_layout(guides = "collect") & 
  theme(
    legend.position = "bottom", 
    legend.key.size = unit(0.2, "cm"), 
    legend.title = element_text(size = 16),
    legend.text = element_text(size = 12)
    )
plot

If necessary, I could probably also facet by the splitting variable ("A" and "B") but would greatly prefer not to for reasons to do with the real world use case.

I've only been using patchwork when putting together plots for this piece of work, so a reasonable chance I'm missing something basic but I cant for the life of me work it out

0 Answers
Related