Crop out ggplot2 whitespace around plot
If you are looking for a solution which also works in R markdown (i.e. output as PDF/HTML), this solved it for me: first set the aspect ratio and then remove the additional margin on the top via the theme()
settings.
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, shape = Species, color = Species)) +
geom_point(size = 5) +
coord_fixed(ratio = 1/2) +
theme(plot.margin=unit(c(-0.30,0,0,0), "null")) # remove margin around plot
See also this blog post for more details.
Session info: MacOs 10.13.6, R 3.6.3, ggplot2_3.3.1
When you use:
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
coord_fixed(ratio = 1) +
ggsave('plot.jpg', width = 6, height = 1.5, dpi = 300)
You get a plot with less white space:
Another option could be to use the png or jpeg device:
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
coord_fixed(ratio = 1)
jpeg('plot.jpg', width = 600, height = 150)
p
dev.off()