2017-03-22 2 views
0

ich mehrere Plots mit einem Gitterbefehl zu erzeugen bin versucht, wie folgt:Erstellen Sie mehrere Plots Gitter mit für

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() 
} 

Das Problem ist, obwohl das einzelne Stück Code funktioniert gut, wenn die for-Schleife ausgeführt wird Die Dateien werden ohne Plot generiert. Der Code funktioniert gut mit anderen Plots, die nicht vom Gitter erzeugt werden. Kann jemand das beheben?

Grüße, David

+0

Mögliches Duplikat [mehr Gitter Plots aus einer Datentabelle erstellen lapply in R mit] (http://stackoverflow.com/questions/30476708/create-multiple-gitter-plots-from-a-datentabelle-using-lapply-in-r) –

+0

Sie brauchen wahrscheinlich 'print (xyplot (...))'. –

Antwort

0

die Operationen in einer Funktion mit lapply für Index-Traversal-Wrapping ist eine skalierbare Lösung. facet_grid von ggplot bietet alternative Zeichenschema.

Beachten Sie die Verwendung von aes_string für die Verwendung mit String-Variablen und as.formula, um dynamische Formeln zu erstellen.

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

Verwandte Themen