0

I am trying to print png (or pdf) outputs using ggplot and the png() device. This works well for individual cases but not when I define it to be part of a function. See my reproducible example below:

# Define the data
test <- data.frame(title=sample(c("a", "b", "c"), 10, replace=T), author=sample(c("X", "Y", "Z"), 10, replace=T), 
                   topic = sample(c("economic", "social"), 10, replace=T), proportion = sample(seq(from = 0, to = 1, length.out = 1000), 10, replace=T))

# Define the first function
library(ggplot2)
produce.myheatmaps <- function(AUTHOR, AUTHOR.GREP, DF){
    ggplot(DF[grep(AUTHOR.GREP, DF$author),], aes(x=topic, y= proportion), fill=proportion) +
        geom_tile() +
        ggtitle(AUTHOR)
}

# This works as expected
produce.myheatmaps("John Doe","Z", test)

# Print - this works
png(file=paste("John Doe", ".png", sep=""),width=12000,height=6000, res=600)
produce.myheatmaps("John Doe", "Z", test)
dev.off()

# Now define a list of authors - which is how my original data is defined
my.authors <- list(
    c("Jane Doe", "Y"),
    c("John Doe", "Z")
)


# Define a second function to print several authors.
print.heat.map <- function(NAMES, DF){
    name <- NAMES[1]
    name2 <- NAMES[2]
    produce.myheatmaps(name, name2, DF)
    ggsave(file=paste(name, ".png", sep=""))
}

# This works too
print.heat.map(my.authors[[1]], test)


# I need (in my original problem) adjust the widht and height
#  I can do that for one author...
png(file=paste(my.authors[[1]][1], ".png", sep=""),width=12000,height=6000, res=600)
produce.myheatmaps(my.authors[[1]][1], my.authors[[1]][2], test)
dev.off()


## But this does not work when I define it to be part of a function
### Any idea why?
print.heat.map <- function(NAMES, DF){
    name <- NAMES[1]
    name2 <- NAMES[2]
    png(file=paste(name, ".png", sep=""),width=12000,height=6000, res=600)
    produce.myheatmaps(name, name2, DF)
    dev.off()
}

# This produces merely white pages
lapply(my.authors, print.heat.map, test)

Any ideas about what is going on here?

Adel
  • 85
  • 2
  • 8
  • R FAQ 7.22, but also see http://stackoverflow.com/questions/7034647/save-ggplot-within-a-function – Brian Diggs Aug 20 '15 at 21:43
  • Thanks Brian! It did answer my question and sorry for not spotting the post before posting the question. For reference of future readers. This works: print.heat.map <- function(NAMES, DF){ name <- NAMES[1] name2 <- NAMES[2] p <- produce.myheatmaps(name, name2, DF) png(file=paste(name, ".png", sep=""),width=12000,height=6000, res=600) print(p) dev.off() } – Adel Aug 21 '15 at 13:09

0 Answers0