Search code examples
rggplot2ggpubrcowplot

Adjust margins around extracted ggplot legend


I want to extract and save/export the legend of a ggplot object. The following code does this perfectly well, using either ggpubr::get_legend() or cowplot::get_legend().

However when the extracted legend is converted back to a ggplot object (for saving), it has massive white margins around it. My question is how to adjust these margins?

# Create a scatter plot
library(ggpubr)
p <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
  color = "Species", palette = "jco",
  ggtheme = theme_minimal())
p

# Extract the legend. Returns a gtable
leg <- get_legend(p)

# Convert to a ggplot object and print
leg <- as_ggplot(leg)
leg

# Save
# ggsave("legend.png")

Here is how I (unsuccessfully) tried to do this.

leg + theme(
  legend.margin=margin(c(0,0,0,0)))

The margins remain massive, despite str(leg) showing that the legend.margins are all '0'.

legend with large white margins!


Solution

  • You can simple change the size of the image (ggsave("legend.png", width = 2, height = 2)):

    library(ggpubr)
    p <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
      color = "Species", palette = "jco",
      ggtheme = theme_minimal())
    leg <- get_legend(p)
    leg <- as_ggplot(leg)
    leg <- leg + theme(
      legend.margin=margin(c(0,0,0,0)))
    ggsave("legend.png", width = 2, height = 2)