Question

Does it take an additional loop to write a series of plots from ggplot to a single .pdf rather than as a separate .pdf for each plot? Otherwise this code does what I want: subset by type, write series of ggplot arrays to pdf--one grid plot for each location overlayed by color-coded years, y axis label is type, x axis label is day. Other suggestions/improvements?

d_ply(m,"type",function(a) {
  p <- ggplot( a, aes(y=result, x=day, color=colorcode)) + geom_point()
  q <-p + plotOptions + ylab(a$type) 
  print(q)
  ggsave(paste(a$type,".pdf"), plot=q)               
  }) 

sample dataframe

 a<-factor(c(rep("A",4),rep("B",4)))
 b<-factor(c(rep("2006",4),rep("2007",4)))
 d<-c(rep(13,4),rep(14,4))
 e<-factor(c(rep("birds",4),rep("fish",4)))
 f<-sample((25:100),8)
 g<-factor(c(rep("2003-12",4),rep("2003",4))) 
 m<-data.frame(a,b,d,e,f,g)
 colnames(m)<-c("location","year","day","type","result","colorcode")

 names(m)<-tolower(names(m))


 backColor <- "moccasin"
 plotOptions <- list(scale_colour_manual(values = c("skyblue","royalblue" ), name="year"), 
                facet_wrap(~ location, ncol=4))

Thanks for any comments.

Update

So, my initial draft of the code tried what you suggested, but the result was an empty pdf:

pdf(file="test.pdf")
d_ply(m,"type",function(a) {
  p <- ggplot( a, aes(y=result, x=day, color=colorcode)) + geom_point()
  p + plotOptions + ylab(a$type) 

  }) 
dev.off()

That was just due to not explicitly printing the update to p? The online discussion about this goes in all sorts of directions, some very complicated, some with calls to ggsave, etc. That's why I wound up with the call to ggsave.

One last question: to combine values in two factor fields for ylab, say to tack on a unit, would something like this work: a[c("f1", "f2"), sep = "")]?

Was it helpful?

Solution 2

If you want multiple plots per PDF file, then this is one way to do it:

pdf("allinone.pdf")
d_ply(m,"type",function(a) {
  p <- ggplot( a, aes(y=result, x=day, color=colorcode)) + geom_point()
  print(p + plotOptions + ylab(a$type))
}) 
dev.off()

OTHER TIPS

Multiple plots in a single pdf:

library(grid)
vplayout <- function(x, y)
  viewport(layout.pos.row = x, layout.pos.col = y)
pdf("AllInOne.pdf", width = 12, height = 12)
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
print(p, vp = vplayout(1, 1))
print(q, vp = vplayout(1, 2))
print(p, vp = vplayout(2, 1))
print(q, vp = vplayout(2, 2))
dev.off()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top