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

时间:2016-02-11 17:29:38

标签: r ggplot2

如何删除ggsave中的白边?

我的问题与Remove white space (i.e., margins) ggplot2 in R完全相同。但是,答案对我来说并不理想。我想给ggsave一个heightweight并希望我的情节(即标题的顶部到x-label的底部),而不是针对固定但未知的宽高比进行反复试验)自动扩展到没有白边的配置。

How can I remove the strange white margin around my .png (plotted with r, ggplot)?提供了一种方法,可以使边距保持透明,但它们仍然存在且情节小于我在保存文件中设置的heightwidth

5 个答案:

答案 0 :(得分:7)

Remove Plot Margins in ggplot2

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

完成工作

答案 1 :(得分:2)

如果您使用的是Unix或Mac OS,则在各种边距选项不够完善的情况下,另一种选择是通过pdfcrop调用系统的能力来使用Unix中可用的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/

答案 2 :(得分:0)

如果不是pdf和pdfcrop,例如您使用的是带有png徽标的png,请在此处查看我的答案:How to save a ggplot2 graphic with the proper aspect ratio?

答案 3 :(得分:0)

this answer链接到this blog post的情况下,有一种解决方案也适用于不同的宽高比。您可以与操作系统无关地在硬盘驱动器上裁剪图像:

knitr::plot_crop()

答案 4 :(得分:0)

我最终在 ggsave 之后添加了这样的命令:

system("/usr/local/bin/mogrify -trim -border 8 -bordercolor white output.png")

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

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

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