与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"))
图:
的[创建从数据表中的R使用lapply多个晶格地块]可能的复制(http://stackoverflow.com/questions/30476708/create-multiple-lattice-plots-from-a-data-table-using-lapply-in-r) –
你可能需要'print(xyplot(...))'。 –