13

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

Community
  • 1
  • 1
0mm3
  • 319
  • 2
  • 16

2 Answers2

8

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()
h3rm4n
  • 4,126
  • 15
  • 21
7

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

mavericks
  • 1,005
  • 17
  • 42
  • 1
    may also be necessary to set the crop options: https://stackoverflow.com/a/57059235/7941188 – tjebo Jun 23 '20 at 09:25