Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot, remove white margins in ggsave/ggplot

Tags:

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.

like image 483
jf328 Avatar asked Feb 11 '16 17:02

jf328


People also ask

How do I change the margins in ggplot2?

Margins in ggplot2. Increase margins. Remove margins. The margins of the plots made with ggplot2 will adjust automatically to new layers, e.g. if you add a title. We have added a black box around the sample plot so you can see how margins change.

How do I save a plot in R using ggsave?

In most cases ggsave () is the simplest way to save your plot, but sometimes you may wish to save the plot by writing directly to a graphics device. To do this, you can open a regular R graphics device such as png () or pdf (), print the plot, and then close the device using dev.off ().

How do I remove the margins from a plot?

The margins are measured with points ( "pt" ), but you can use other unit measure in the unit argument, like centimeters. Type ?unit to see all the possible measures. To remove the margins set all values to 0. Note that there is still space to fit all the elements of the plot.

How do I remove the axes from a ggplot2 plot?

Unfortunately, you still need to add labs (x = NULL, y = NULL), because there is no way in ggplot2's theme machinery to remove the axes completely. And you need to set expand=c (0,0) in the scale parameters to make sure the scale doesn't extend beyond your data range. After using your code, I see more clearly what you're looking for. This:


2 Answers

Found the answer from Remove Plot Margins in ggplot2

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

does the job

like image 145
jf328 Avatar answered Sep 20 '22 18:09

jf328


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()
like image 26
JaBe Avatar answered Sep 20 '22 18:09

JaBe