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

我想提取和保存/导出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)))

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

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

yuelao0308 回答:调整提取的ggplot图例周围的边距

您可以简单地更改图像的大小(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)))
ggsave("legend.png",height = 2)
本文链接:https://www.f2er.com/3057667.html

大家都在问