R ggplot,删除 ggsave/ggplot 中的白边

R ggplot, remove white margins in ggsave/ggplot

如何去除 ggsave 中的白边?

我的问题和Remove white space (i.e., margins) ggplot2 in R一模一样。但是,那里的答案对我来说并不理想。我想给 ggsave 一个 heightweight 并想要我的情节(即标题顶部到 [=24 底部),而不是反复试验=]) 自动扩展到没有白边的配置。

How can I remove the strange white margin around my .png (plotted with r, ggplot)? 给出了一种使边距透明的方法,但它们仍然存在并且绘图小于 heightwidth 我在保存的文件中设置。

Remove Plot Margins in ggplot2

找到答案
theme(plot.margin=grid::unit(c(0,0,0,0), "mm"))

做这份工作

如果您使用的是 Unix 或 Mac OS,当各种边距选项没有足够调整时,另一种选择是使用 Unix 中可用的 pdfcrop 命令,通过 R调用系统命令的能力:

# after saving image, run pdfcrop 
system2(command = "pdfcrop", 
        args    = c("name_or_path_of_file_before_crop.pdf", 
                    "name_or_path_of_file_after_crop.pdf") 
        )

更多信息,请参阅:https://robjhyndman.com/hyndsight/crop-r-figures/

如果您不喜欢 pdf 和 pdfcrop,例如您使用带有 png 徽标的 png 格式工作 - 那么请在此处查看我的回答:How to save a ggplot2 graphic with the proper aspect ratio?

this answer linking to this blog post 中有一个解决方案也适用于不同的纵横比。您可以裁剪硬盘上的图像,独立于 OS:

knitr::plot_crop()

我最终在 ggsave:

之后添加了这样的命令
system("/usr/local/bin/mogrify -trim -border 8 -bordercolor white output.png")

-trim 删除现有边距,-border 8 -bordercolor white 在绘图周围添加一个小的 8px 边距。

对于具有灰色背景的图,图的边缘周围留下了一些白色像素,因此我使用 -shave 选项删除了一些额外的像素:

system("/usr/local/bin/mogrify -trim -shave 4x4 output.png")