我正在尝试使用ggplot和png()设备打印png(或pdf)输出。这适用于个别情况,但在我将其定义为函数的一部分时则不适用。请参阅下面我可重复的示例:
# 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)
关于这里发生了什么的任何想法?