David Manteigas
David Manteigas

Reputation: 19

Create multiple lattice plots using for

I'm trying to generate multiple plots using a lattice command, as follows:

variable <- (string with variable names)

for (i in 1:X){

 mypath <- paste(i,' - ',variable[i],'.png',sep='')
 png(mypath,width=760)

  xyplot(get(variable[i]) ~ GroupVariable, groups = IDvariable,
         data = dataset,
         type = "l" )

 dev.off()
}

The problem is, although the individual piece of code works fine, when executing the for loop the files are generated without any plot. The code works fine with other plots not generated by lattice. Does anyone know how to fix this?

Regards, David

Upvotes: 0

Views: 463

Answers (2)

Max Berentelg
Max Berentelg

Reputation: 11

print(xyplot(...)) should help

The lattice function xyplot() does not produce any output when it is called in another function (i.e. a for loop). Hence, in a loop the output of xyplot() has to be printed in in an extra step.

I had the same problem and this post explained everything: https://stat.ethz.ch/pipermail/r-help/2005-May/071467.html

To solve your problem you have to put the xyplot() call inside print(). Your code example should work like this:

variable <- (string with variable names)

for (i in 1:X){

 mypath <- paste(i,' - ',variable[i],'.png',sep='')
 png(mypath,width=760)

 print(xyplot(get(variable[i]) ~ GroupVariable, groups = IDvariable,
        data = dataset,
        type = "l"))
 dev.off()
}

Upvotes: 1

Silence Dogood
Silence Dogood

Reputation: 3597

Wrapping the operations in a function with lapply for index traversal is a scalable solution. facet_grid from ggplot provides alternative plotting scheme.

Note usage of aes_string for usage with string variables and as.formula to contruct dynamic formulae.

data(mtcars)

library("lattice")
library("ggplot2")


 fn_exportPlot = function(
 dataObj = mtcars, 
 indepVar  = "cyl", 
 depVar = "mpg",
 groupVar = "am",
 plotEngine=c("lattice","ggplot")) {

filePath =  paste0(indepVar,"_",plotEngine,'.png')

png(filePath,width=760) 


if(plotEngine=="lattice"){ 

formulaVar = as.formula(paste0(depVar," ~ ",indepVar,"|",groupVar))

 print(xyplot(formulaVar,data=dataObj))

}else{

 groupForm = as.formula(paste0("~ ",groupVar))

 gg = ggplot(mtcars,aes_string(indepVar,depVar)) + geom_point(shape=1) + facet_grid(groupForm)

 print(gg)


}

dev.off()


}

varList = c("cyl","disp")

lapply(varList,function(x) fn_exportPlot(indepVar = x,plotEngine="lattice") )
lapply(varList,function(x) fn_exportPlot(indepVar = x,plotEngine="ggplot") )

Plots: enter image description here

enter image description here

Upvotes: 0

Related Questions