调整提取的 ggplot 图例周围的边距

Adjust margins around extracted ggplot legend

我想提取并save/export ggplot 对象的图例。下面的代码使用 ggpubr::get_legend() 或 cowplot::get_legend().

完美地做到了这一点

然而,当提取的图例转换回 ggplot 对象(用于保存)时,它周围有大量的白色边距。我的问题是如何调整这些边距?

# 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")

以下是我(未成功)尝试执行此操作的方式。

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

尽管 str(leg) 显示 legend.margins 全部为“0”,但边距仍然很大。

您可以简单地更改图像的大小 (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)