Is there a way to remove the white space surrounding a ggplot2 plot when the shape has been changed using coord_fixed()
? I would like the white space above and below to be cropped away so that only the plotting area and axis labels remain. I am rendering the plot output in an R markdown file without saving.
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p + coord_fixed(ratio = 1)
The code below produces the following plot:
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()
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
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