I've been attempting to extract a ggplot2()
legend with cowplot::get_legend()
following the instructions outlined in a previous post. I aim to save this as an image to add to another plot and would like to change the background colour to "#F0F8FF"
and remove the majority of the blank space that I end up with after running grid.draw(legend)
. Is there a way to do this? Thanks.
# install.packages("cowplot")
set.seed(10)
mydata <- data.frame(
X = rnorm(80, 8, 4),
Y = rnorm(80, 7, 8)
)
p <- ggplot(mydata, aes(x = X, y = Y, colour = Y)) +
geom_point()
legend <- cowplot::get_legend(p)
grid.newpage()
grid.draw(legend)
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")