3

I would like to remove the white border in a .png output file, using ggplot2. I'm using Windows 10 with Rstudio, ggplot2, and geom_raster. After spending time searching on forums, and playing with some parameters, I ended up with this codes (that still does not work):

library(ggplot2)
library(datasets)

png(file = "Out.png")

par(mar=rep(0, 4), plt=c(0.1,0.9,0.1,0.9), xpd=NA)

ggplot(faithfuld, aes(waiting, eruptions)) +
geom_raster(aes(fill = density))+
theme(axis.line        = element_blank(),
      axis.text        = element_blank(),
      axis.ticks       = element_blank(),
      axis.title       = element_blank(),
      panel.background = element_blank(),
      panel.border     = element_blank(),
      panel.margin = unit(0,"null"),
      legend.position = "none",
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      plot.background  = element_blank(),
      plot.margin = rep(unit(0,"null"),4))

dev.off()

This code gives this png:

enter image description here

Sumedh
  • 4,835
  • 2
  • 17
  • 32
Maurice clere
  • 31
  • 1
  • 4
  • Some answers here: [how-do-i-remove-margins-surrounding-the-plot-area](http://stackoverflow.com/questions/31254533/when-using-ggplot-in-r-how-do-i-remove-margins-surrounding-the-plot-area/31256788#31256788) – Sandy Muspratt Aug 03 '16 at 22:28
  • and here: [ggplot2 theme with no axes or grid](http://stackoverflow.com/questions/14313285/ggplot2-theme-with-no-axes-or-grid). – cuttlefish44 Aug 04 '16 at 06:02
  • Thanks for your different links to similar cases. After some tries, it seems that only the one provided by Floo using the cowplot package worked in this case (maybe because of geom_raster or package versions). – Maurice clere Aug 05 '16 at 16:54
  • It looks like you were missing the `scale_*_*(expand = c(0, 0))` for both axes and `axis.ticks.length = unit(0, "mm"))`. This is in [one of the given links](http://stackoverflow.com/questions/31254533/when-using-ggplot-in-r-how-do-i-remove-margins-surrounding-the-plot-area/31256788#31256788), but not quite in the marked duplicate. – aosmith Aug 05 '16 at 17:17

1 Answers1

3

Even when it is a little bit hacky you can use the cowplot-Package to achieve that as follows:

library(ggplot2)
library(datasets)
require(cowplot)
base <- ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density)) +
  theme_nothing() + labs(x = NULL, y = NULL) 
plot_grid(base, scale=1.1)

- theme_nothing() + labs(x = NULL, y = NULL) is a short handle for what you did with theme(...)
- plot_grid(..., scale=1.1) is the important part as it resizes the plot to overlap the white border.

This gives you:

enter image description here

Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • Hi Floo, yes it works. How do you figure out the 1.1. Just to add an information: it will work if we don't use legend. But that is fine enough! Thanks very much. – Maurice clere Aug 04 '16 at 20:17