Skip to content

get_legend only works with default legend position, will not detect if legend is "bottom" for instance  #205

@jkylearmstrong

Description

@jkylearmstrong
library(cowplot)
library(ggplot2)

theme_set(theme_half_open())

p1 <- ggplot(mtcars, aes(mpg, disp)) + 
  geom_line()

plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5) +
  theme(legend.position='bottom')

legend <- get_legend(plot.mpg)

plot.mpg <- plot.mpg + theme(legend.position='none')
# Now plots are aligned vertically with the legend to the right
ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'),
                 plot_grid(NULL, legend, ncol=1),
                 rel_widths=c(1, 0.2)))
sessionInfo()
R version 4.4.0 (2024-04-24 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 22631)

Matrix products: default


locale:
[1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8   
[3] LC_MONETARY=English_United States.utf8 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.utf8    

time zone: America/New_York
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
[1] ggplot2_3.5.1 cowplot_1.1.3

loaded via a namespace (and not attached):
 [1] labeling_0.4.3    utf8_1.2.4        R6_2.5.1          tidyselect_1.2.1 
 [5] farver_2.1.2      magrittr_2.0.3    gtable_0.3.5      glue_1.7.0       
 [9] tibble_3.2.1      pkgconfig_2.0.3   generics_0.1.3    dplyr_1.1.4      
[13] lifecycle_1.0.4   cli_3.6.2         fansi_1.0.6       scales_1.3.0     
[17] grid_4.4.0        vctrs_0.6.5       withr_3.0.0       renv_1.0.7       
[21] compiler_4.4.0    rstudioapi_0.16.0 tools_4.4.0       pillar_1.9.0     
[25] munsell_0.5.1     colorspace_2.1-0  rlang_1.1.4  

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions