首页 文章

使用for创建多个点阵图

提问于
浏览
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循环时,生成的文件没有任何绘图 . 该代码适用于非格子生成的其他图 . 有谁知道如何解决这一问题?

问候,大卫

1 回答

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

    Plots:
    enter image description here

    enter image description here

相关问题