简体   繁体   中英

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'.

大白边的传奇!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM