簡體   English   中英

調整提取的 ggplot 圖例周圍的邊距

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM