17
votes

How can I remove the white margins in ggsave?

My question is exactly the same as Remove white space (i.e., 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.

5

5 Answers

21
votes

Found the answer from Remove Plot Margins in ggplot2

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

does the job

5
votes

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/

4
votes

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()
1
votes

If pdf and pdfcrop aren't your thing, for example you work in png with a png logo - then see my answer here: How to save a ggplot2 graphic with the proper aspect ratio?

0
votes

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