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.
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.
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 ().
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.
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:
Found the answer from Remove Plot Margins in ggplot2
theme(plot.margin=grid::unit(c(0,0,0,0), "mm"))
does the job
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With