@@ -575,6 +575,10 @@ Guides <- ggproto(
575
575
widths <- lapply(grobs , `[[` , " widths" )
576
576
heights <- lapply(grobs , `[[` , " heights" )
577
577
578
+ # Check whether legends are stretched in some direction
579
+ stretch_x <- any(unlist(lapply(widths , unitType )) == " null" )
580
+ stretch_y <- any(unlist(lapply(heights , unitType )) == " null" )
581
+
578
582
# Global justification of the complete legend box
579
583
global_just <- paste0(" legend.justification." , position )
580
584
global_just <- valid.just(calc_element(global_just , theme ))
@@ -617,14 +621,21 @@ Guides <- ggproto(
617
621
}
618
622
619
623
spacing <- convertWidth(theme $ legend.spacing.x , " cm" )
620
- widths <- redistribute_null_units(widths , spacing , margin , " width" )
621
624
heights <- unit(height_cm(lapply(heights , sum )), " cm" )
622
625
626
+ if (stretch_x ) {
627
+ widths <- redistribute_null_units(widths , spacing , margin , " width" )
628
+ vp_width <- unit(1 , " npc" )
629
+ } else {
630
+ widths <- inject(unit.c(!!! lapply(widths , sum )))
631
+ vp_width <- sum(widths , spacing * (length(grobs ) - 1L ))
632
+ }
633
+
623
634
# Set global justification
624
635
vp <- viewport(
625
636
x = global_xjust , y = global_yjust , just = global_just ,
626
637
height = max(heights ),
627
- width = sum( widths , spacing * (length( grobs ) - 1L ))
638
+ width = vp_width
628
639
)
629
640
630
641
# Initialise gtable as legends in a row
@@ -648,13 +659,20 @@ Guides <- ggproto(
648
659
}
649
660
650
661
spacing <- convertHeight(theme $ legend.spacing.y , " cm" )
651
- heights <- redistribute_null_units(heights , spacing , margin , " height" )
652
662
widths <- unit(width_cm(lapply(widths , sum )), " cm" )
653
663
664
+ if (stretch_y ) {
665
+ heights <- redistribute_null_units(heights , spacing , margin , " height" )
666
+ vp_height <- unit(1 , " npc" )
667
+ } else {
668
+ heights <- inject(unit.c(!!! lapply(heights , sum )))
669
+ vp_height <- sum(heights , spacing * (length(grobs ) - 1L ))
670
+ }
671
+
654
672
# Set global justification
655
673
vp <- viewport(
656
674
x = global_xjust , y = global_yjust , just = global_just ,
657
- height = sum( heights , spacing * (length( grobs ) - 1L )) ,
675
+ height = vp_height ,
658
676
width = max(widths )
659
677
)
660
678
@@ -670,7 +688,6 @@ Guides <- ggproto(
670
688
}
671
689
672
690
# Add margins around the guide-boxes.
673
- margin <- theme $ legend.box.margin %|| % margin()
674
691
guides <- gtable_add_padding(guides , margin )
675
692
676
693
# Add legend box background
@@ -684,6 +701,12 @@ Guides <- ggproto(
684
701
)
685
702
686
703
# Set global margin
704
+ if (stretch_x ) {
705
+ global_margin [c(2 , 4 )] <- unit(0 , " cm" )
706
+ }
707
+ if (stretch_y ) {
708
+ global_margin [c(1 , 3 )] <- unit(0 , " cm" )
709
+ }
687
710
guides <- gtable_add_padding(guides , global_margin )
688
711
689
712
guides $ name <- " guide-box"
0 commit comments