Skip to content

Commit 0033fc0

Browse files
authored
Rework add_guides for arbitrary guide positions (#339)
1 parent fca5e30 commit 0033fc0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

R/plot_patchwork.R

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,39 @@ add_strips <- function(gt) {
684684
add_guides <- function(gt, collect = FALSE) {
685685
panel_loc <- find_panel(gt)[, c('t', 'l', 'b', 'r')]
686686
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+
687720
guide_loc <- gt$layout[guide_ind, c('t', 'l', 'b', 'r')]
688721
guide_pos <- if (nrow(guide_loc) == 0) {
689722
'none'

0 commit comments

Comments
 (0)