Home > Enterprise >  How to remove majority of blank space from get_legend()?
How to remove majority of blank space from get_legend()?

Time:09-14

I've been attempting to extract a ggplot2() legend with cowplot::get_legend() following the instructions outlined in a previous enter image description here

CodePudding user response:

The amount of white space depends on the size of the graphics device, e.g. when you reduce the size of the plotting window the amount of white space is reduced.

Hence, to save the legend as an image without white space you have to set the size accordingly. To this end you could e.g. use grid::widthDetails and grid::heightDetails to get the width and height of the legend grob which could then be used to save the legend without any white space:

Note: I have set the background fill for the legend via theme(legend.background = element_rect(fill = "#F0F8FF"))

set.seed(10)
mydata <- data.frame(
  X = rnorm(80, 8, 4),
  Y = rnorm(80, 7, 8)
)

library(ggplot2)
library(cowplot)
library(grid)

p <- ggplot(mydata, aes(x = X, y = Y, colour = Y))  
  geom_point()  
  theme(legend.background = element_rect(fill = "#F0F8FF"))

legend <- cowplot::get_legend(p)

# Get width and height
widthDetails(legend)
#> [1] sum(0.5null, 0cm, 1.72798867579909cm, 0cm, 0.5null)
heightDetails(legend)
#> [1] sum(0.5null, 0cm, 3.9919047869102cm, 0cm, 0.5null)

# Save
ggsave("legend.png", legend, width = 1.72798867579909, height = 3.9919047869102, unit = "cm")

enter image description here

  • Related