简体   繁体   中英

R ggplot, remove white margins in ggsave/ggplot

How can I remove the white margins in ggsave?

My question is exactly the same as Remove white space (ie, margins) ggplot2 in R . However, the answer there isn't ideal for me. Instead of trial and error for a fixed but unknown aspect ratio, I would like to give ggsave a height and weight and want my plot (ie top of title to bottom of x-label) to automatically expand to that configuration without white margin.

How can I remove the strange white margin around my .png (plotted with r, ggplot)? gives a way to make the margin transparent, but they are still there and the plot is smaller than height and width I set in the saved file.

Found the answer from Remove Plot Margins in ggplot2

theme(plot.margin=grid::unit(c(0,0,0,0), "mm"))

does the job

If you're using Unix or Mac OS, another option when the various margin options aren't trimming enough is to use the pdfcrop command available within Unix through R 's ability to invoke system commands:

# 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") 
        )

For more, see: https://robjhyndman.com/hyndsight/crop-r-figures/

In this answer linking to this blog post there is a solution which also works for different aspect ratios. You can crop the image on your hard drive, independently of OS:

knitr::plot_crop()

如果 pdf 和pdfcrop不是你的东西,例如你在带有 png 标志的 png 中工作 - 然后在这里看到我的答案: 如何以适当的纵横比保存 ggplot2 图形?

I ended up adding a command like this after ggsave :

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

-trim removes an existing margin and -border 8 -bordercolor white adds a small 8px margin around the plot.

For a plot that had a gray background, a few white pixels were left around the edges of the plot, so I used the -shave option to remove a few extra pixels:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM