17

I save plots with ggplot as .png. The background has to be black, but there is allways a small white margin (only top, down an left; not right).

How can I remove this margin?

Thank you!

Here is my Code

library(ggplot2)
require(grid)


dat <- data.frame("xvar"=runif(500, 1, 10), 
              "yvar"=runif(500, 1, 10))

n <- 1
for(i in 1:n){
png(file=paste("green", i, ".png", sep=""), width=400, height=400)
  x <- sample(500, 50)
  i <- ggplot(data=dat[x,], aes(x=xvar, y=yvar))+
geom_point(col="green", size=3,shape=15)+
  theme(panel.background=element_rect(fill="black"), panel.grid.minor=element_blank(),
     panel.grid.major=element_blank(), axis.text.x=element_blank(), axis.text.y=
     element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(),
    axis.ticks=element_blank(), plot.background=element_rect(fill="black"), 
    panel.margin = unit(c(0,0,0,0), "cm"), plot.margin = unit(c(0,0,0,0), "cm"))+
  scale_x_continuous()
print(i)
dev.off() }

Example

enter image description here

joran
  • 169,992
  • 32
  • 429
  • 468
Markus Germar
  • 223
  • 2
  • 6
  • i don't see it; have you tried other devices (eg pdf, cairo_png, quartz_png, etc.?) – baptiste May 08 '13 at 13:36
  • +1 for good first question on SO, including reproducible data and code. I also am seeing a white margin using R 2.15.3 on Windows 7 x64, on left and bottom sides of the png image. Not sure what is causing it though. – SlowLearner May 08 '13 at 14:37
  • The margin is really small (~ 1 pix). I have the same problem with all devices. – Markus Germar May 08 '13 at 14:43
  • I'm using win 7 x64, R 3.0.0 and R-Studio 0.97.449. – Markus Germar May 08 '13 at 14:46
  • I see it as well (or at least, something) on OSX R 3.0.0. I added a clearer picture of what I see in the lower left. Feel free to remove it if it doesn't reflect what you're asking about. – joran May 08 '13 at 15:44
  • In my case, it is a white line. It can be seen when clicking right on my picture and open it in a new windows. – Markus Germar May 08 '13 at 16:05
  • 4
    This fix works on my setup: `plot.background=element_rect(fill="black", colour=NA)` – bdemarest May 08 '13 at 16:53
  • @bdemarest Can you make that an answer so that we can up-vote it and Markus can accept it (so we all know it is solved)? – Brian Diggs May 08 '13 at 21:38

1 Answers1

14

The line you are seeing is the default outline colour of the plot.background rectangle element. You can remove it by setting colour to NA in your theme() call:

theme(plot.background=element_rect(fill="black", colour=NA))
bdemarest
  • 14,397
  • 3
  • 53
  • 56