Search code examples
rggplot2whitespacemargincrop

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


Solution

  • 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()