Why am I not able to collect guides and axes in patchwork?

Hi ggplot2 and patchwork experts,

I was wondering why am I not able to collect guides and axes in the example below? What am I missing??

Dave

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.4.2
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(patchwork)
#> Warning: package 'patchwork' was built under R version 4.4.1
library(palmerpenguins)
  

p1 <- penguins |>
  filter(island == "Biscoe") |> 
  ggplot() +
  geom_point(
    aes(x = flipper_length_mm,
    y = flipper_length_mm,
    col = species),
    size = 10,
  ) +
  expand_limits(y = range(penguins$flipper_length_mm, na.rm = TRUE))

p2 <- penguins |>
  filter(island == "Dream") |>
  ggplot() +
  geom_point(
    aes(x = flipper_length_mm,
        y = flipper_length_mm,
        col = species),
    size = 10,
  ) +
  expand_limits(y = range(penguins$flipper_length_mm, na.rm = TRUE))

(p1 + p2)  |> 
  plot_layout(guides = 'collect', axes = "collect")
#> $ncol
#> Warning: Removed 1 row containing missing values or values outside the scale range
#> (`geom_point()`).

#> 
#> $nrow
#> list()
#> attr(,"class")
#> [1] "waiver"
#> 
#> $byrow
#> list()
#> attr(,"class")
#> [1] "waiver"
#> 
#> $widths
#> list()
#> attr(,"class")
#> [1] "waiver"
#> 
#> $heights
#> list()
#> attr(,"class")
#> [1] "waiver"
#> 
#> $guides
#> [1] "collect"
#> 
#> $tag_level
#> list()
#> attr(,"class")
#> [1] "waiver"
#> 
#> $axes
#> [1] "collect"
#> 
#> $axis_titles
#> [1] "collect"
#> 
#> $design
#> list()
#> attr(,"class")
#> [1] "waiver"
#> 
#> attr(,"class")
#> [1] "plot_layout"

Created on 2024-12-13 with reprex v2.1.1

I am not exactly sure what you want it may be you need the

plot_layout(guides = 'collect', axes = "collect")

with each plot'

Does this help

library(ggplot2)
library(dplyr)
library(patchwork)
library(palmerpenguins)


pp1 <- penguins |>
  filter(island == "Biscoe") |> 
  ggplot() +
  geom_point(
    aes(x = flipper_length_mm,
        y = flipper_length_mm,
        col = species),
    size = 10,
  ) +
  expand_limits(y = range(penguins$flipper_length_mm, na.rm = TRUE)) +
  plot_layout(guides = 'collect', axes = "collect")

pp2 <- penguins |>
  filter(island == "Dream") |>
  ggplot() +
  geom_point(
    aes(x = flipper_length_mm,
        y = flipper_length_mm,
        col = species),
    size = 10,
  ) +
  expand_limits(y = range(penguins$flipper_length_mm, na.rm = TRUE)) +
  plot_layout(guides = 'collect', axes = "collect")

pp1 + pp2
  
1 Like

Worked it out. I used a |> instead of a +

Ah, nice. I would not have thought of a +. I think my solution is cleaner. You only need one legend if you use a title or some text to label the charts.

1 Like