使用

2017-03-22 15 views
0

我试图使用产生晶格命令多条曲线创建多个格子图,如下:使用

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

问题是,尽管代码的单件工作正常,for循环执行时生成的文件没有任何情节。该代码可以很好地与其他不是由点阵生成的图形一起工作。有谁知道如何解决这一问题?

问候, 大卫

+0

的[创建从数据表中的R使用lapply多个晶格地块]可能的复制(http://stackoverflow.com/questions/30476708/create-multiple-lattice-plots-from-a-data-table-using-lapply-in-r) –

+0

你可能需要'print(xyplot(...))'。 –

回答

0

lapply函数索引遍历包装纸的业务是一个可扩展的解决方案。来自ggplot的 facet_grid提供了替代绘图方案。

aes_string用于字符串变量的使用和as.formula注意使用去构造动态公式。

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")) 

图: enter image description here

enter image description here