28

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.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
jf328
  • 6,841
  • 10
  • 58
  • 82

5 Answers5

37

Found the answer from Remove Plot Margins in ggplot2

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

does the job

Community
  • 1
  • 1
jf328
  • 6,841
  • 10
  • 58
  • 82
  • 3
    When the aspect ratio is changed with e.g. `theme(aspect.ratio=9/16)` this will not work. – JaBe Nov 17 '20 at 17:06
  • 4
    Unsure why this answer was accepted. This merely removes the margin such that the axis labels,chart title, and panel are all have 0 margin. The white bordering will still be printed with ggsave. – jparanich Feb 01 '22 at 21:41
  • @JaBe, any tips on how to make it work with theme(aspect.ratio=...)? Been looking for this for days. – wptmdoorn Jun 28 '23 at 11:56
8

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()
JaBe
  • 664
  • 1
  • 8
  • 27
6

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/

Omar Wasow
  • 1,870
  • 24
  • 24
1

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?

Scrope
  • 386
  • 2
  • 5
0

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")
nisetama
  • 7,764
  • 1
  • 34
  • 21