0

Suppose I am in this case:

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep=",")
nba <- nba[order(nba$PTS),]
row.names(nba) <- nba$Name

nba_matrix <- data.matrix(nba)

library(ggplot2)
library(reshape)
nba.m <- melt(nba)
library(plyr)
library(scales)
nba.m <- ddply(nba.m, .(variable), transform, rescale=rescale(value))
(p <- ggplot(nba.m, aes(variable, Name)) + geom_tile(aes(fill = rescale), colour = "white") + 
      scale_fill_gradient(low = "white", high = "steelblue"))

Now I want to create a series of images contained in the same pdf document (not n pdf documents):

listaNbA <- list(nba.m,nba.m)
pdf("bennagoal.pdf")

  (p <- ggplot(listaNbA[[1]], aes(variable, Name)) + geom_tile(aes(fill = rescale), colour = "white") +
     scale_fill_gradient(low = "white", high = "purple")+
     theme(axis.text.x = element_text(angle = 45, hjust = 1))+
     geom_text(aes(label=value))
  )

  (p <- ggplot(listaNbA[[2]], aes(variable, Name)) + geom_tile(aes(fill = rescale), colour = "white") +
  scale_fill_gradient(low = "white", high = "purple")+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))+
  geom_text(aes(label=value))
  )

dev.off()

It works producing a pdf file with two pages. Now I want to do the same, but using a for loop:

listaNbA <- list(nba.m,nba.m)
pdf("jamesotto.pdf")
for(i in 1:2){

(p <- ggplot(listaNbA[[i]], aes(variable, Name)) + geom_tile(aes(fill = rescale), colour = "white") +
  scale_fill_gradient(low = "white", high = "purple")+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))+
  geom_text(aes(label=value))
)

}
dev.off()

The second code produces an empty pdf file. Why?

Andrea Ianni
  • 829
  • 12
  • 24
  • Actually it's pretty different. In the question you linked they wanted simply produce n pdf's, every one containing a figure. I want to produce a unique pdf containing n pages. If I do it by hand (without the loop structure) it works. The loop structure does not. – Andrea Ianni May 04 '16 at 15:21
  • 1
    add `print(p)` the line above `}`. You have to explicitly use the `print` function within a `for` loop. – lmo May 04 '16 at 15:27
  • @Imo Putting the assignment in parens can actually be an obtuse, hard to read way of triggering the print method. But you're right, explicitly calling `print` would probably be better practice. – joran May 04 '16 at 15:32
  • Thanks Imo. It has worked perfectly! – Andrea Ianni May 04 '16 at 15:43

0 Answers0