在 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") )
Plots: