java生成点阵图_使用for创建多个点阵图

这篇博客介绍了如何使用R语言的lapply函数结合ggplot2和lattice库生成多张点阵图。通过自定义函数fn_exportPlot,以不同的独立变量为依据,动态构建并保存了点阵图,支持两种绘图引擎:lattice和ggplot。示例中展示了针对'cyl'和'disp'两个变量分别生成点阵图的过程。
摘要由CSDN通过智能技术生成

在 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:

b8063e58-5e2c-4c85-b06a-c650f9237eec.png

ca64ed2c-f165-495e-a11f-1668ecdb4d3c.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值