JasonMond
JasonMond

Reputation: 1450

Reason why PNG figure is empty and solutions

I have the following function in R

pairwise.yearly.plot <- function(data.source, data.target, suffix=".PR", years=2003:2007) {
  # plot pairwise year data for time series representation of data                                                                                                                                                                 
  first <- years[1]
  last <- years[length(years)]
  nc <- last - first #2007-2003                                                                                                                                                                                                    
  par(mfrow=c(nc, nc))
  for(y1 in years) {
    for(y2 in years) {
      if(y1 < y2) {
        year.source <- num.to.colname(y1);
        if(suffix == ".PE") {
          year.target <- paste(num.to.colname(y1), y2, sep=".");
        } else {
          year.target <- paste(num.to.colname(y2), suffix, sep="");
        }
        plot(data.source[[year.source]], data.target[[year.target]], xlab=y1, ylab=paste(y2, suffix,sep=""))
      }
      else if(y1 > y2) {
        frame()
      }
    }
  }
}

When I invoke this with:

png("output.png")
pairwise.yearly.plot(foo, bar)
dev.off()

I get an empty png file. This doesn't happen when I set the graphic device to pdf. Could anybody tell me why and how to fix this?

Upvotes: 0

Views: 3005

Answers (2)

Khalil Youssefi
Khalil Youssefi

Reputation: 414

In case you are using ggplot, use this template:

png("PNG_FILE.png")
g <- ggplot(....)
print(g)
dev.off()

Upvotes: 0

kith
kith

Reputation: 5566

The problem is that you're calling more plot commands than you've prepared for with par(mfrow=c(nc, nc))

if nc is 4, then you're prepping 16 cells to draw on, but the loops account for 25 operations. If the last of those extra operations is frame() you'll end up with a blank picture.

Upvotes: 2

Related Questions