@@ -684,6 +684,39 @@ add_strips <- function(gt) {
684
684
add_guides <- function (gt , collect = FALSE ) {
685
685
panel_loc <- find_panel(gt )[, c(' t' , ' l' , ' b' , ' r' )]
686
686
guide_ind <- which(grepl(' guide-box' , gt $ layout $ name ))
687
+
688
+ if (length(guide_ind ) == 5 ) {
689
+ # For ggplot2 >3.5.0, we don't need to add extra space for missing legends,
690
+ # as every position already has relevant cells in the gtable.
691
+ if (! collect ) {
692
+ return (gt )
693
+ }
694
+ # We need to collect guides from multiple cells in the gtable instead.
695
+ guide_loc <- gt $ layout [guide_ind , ]
696
+ guide_pos <- gsub(" guide-box-" , " " , guide_loc $ name )
697
+
698
+ # Set space for guides to zero
699
+ space_pos <- ifelse(guide_pos %in% c(' left' , ' top' ), 1L , - 1L )
700
+ lr <- guide_pos %in% c(' left' , ' right' )
701
+ col <- guide_loc $ l [lr ]
702
+ gt $ widths [c(col , col + space_pos [lr ])] <- unit(0 , " mm" )
703
+ tb <- guide_pos %in% c(' top' , ' bottom' )
704
+ row <- guide_loc $ t [tb ]
705
+ gt $ heights [c(row , row + space_pos [tb ])] <- unit(0 , " mm" )
706
+
707
+ # Collect guides
708
+ collection <- lapply(gt $ grobs [guide_ind ], function (box ) {
709
+ box $ grobs [grepl(' guides' , box $ layout $ name )] # NULL if legend is empty
710
+ })
711
+ collection <- unlist(collection , recursive = FALSE ) # drops NULL
712
+ gt $ collected_guides <- collection
713
+
714
+ # Remove guides from gtable
715
+ gt $ grobs [guide_ind ] <- NULL
716
+ gt $ layout <- gt $ layout [- guide_ind , ]
717
+ return (gt )
718
+ }
719
+
687
720
guide_loc <- gt $ layout [guide_ind , c(' t' , ' l' , ' b' , ' r' )]
688
721
guide_pos <- if (nrow(guide_loc ) == 0 ) {
689
722
' none'
0 commit comments