Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop out ggplot2 whitespace around plot

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:

plot with white space

like image 933
0mm3 Avatar asked Feb 19 '17 15:02

0mm3


2 Answers

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:

enter image description here

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()
like image 51
h3rm4n Avatar answered Oct 14 '22 18:10

h3rm4n


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

enter image description here

See also this blog post for more details.

Session info: MacOs 10.13.6, R 3.6.3, ggplot2_3.3.1

like image 37
mavericks Avatar answered Oct 14 '22 19:10

mavericks