[英]Adjust margins around extracted ggplot legend
我想提取并保存/导出 ggplot object 的图例。 下面的代码使用 ggpubr::get_legend() 或 cowplot::get_legend() 可以很好地做到这一点。
但是,当提取的图例转换回 ggplot object(用于保存)时,它周围有大量的白色边距。 我的问题是如何调整这些边距?
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.