如何将R语言for循环生成的多组数据合并绘制到同一张散点图
解决方案
核心调整逻辑
- 预先创建列表存储每个性状(trait)的p值计算结果,避免循环过程中数据被覆盖
- 先完成所有性状的关联分析计算,再统一绘图:先绘制符合坐标轴范围的空白画布,再逐个添加不同颜色的散点
- 最后增加图例区分不同性状,也可按需调整点的透明度优化重叠展示效果
修改后完整代码
pts <- read.csv('data_rqtl_phenotypes.csv',as.is=T) gts <- read.csv('data_rqtl_genotypes.csv',as.is=T) gts <- gts[,c(1,grep('2B',gts[1,]))]### use only 1B gts <- gts[,!apply(gts[2,],1,duplicated)]### remove duplicated dim(gts)### 93 229 map <- gts[1:2,]### salvage map gts <- gts[-c(1:2),] gts[gts=='-'] <- NA testdfr <- merge(pts,gts,by='id') testdfr[1:5,1:10] # 预先定义存储所有性状p值的列表 all_pvalue <- list() trait_names <- colnames(pts)[-1] # 自定义颜色组,数量自动匹配性状数量,也可替换为rainbow(length(trait_names))自动生成 trait_colors <- c("red","blue","green","orange","purple","brown")[1:length(trait_names)] # 若重叠严重可调整透明度,示例:trait_colors <- adjustcolor(trait_colors, alpha.f = 0.6) # 第一步:循环计算所有性状的p值,统一存入列表 for( trait in trait_names) { print(trait) pValueL <- c() for(marker in colnames(gts)) { model <- try(lm(testdfr[,trait]~testdfr[,marker])) { if(any("try-error"%in%class(model))) print('not enough data for a test') else { modelsum <- summary(model) coeffs <- modelsum$coefficient pValue=coeffs[grep('[AB]$',row.names(coeffs)),grep('Pr',colnames(coeffs))] if(length(pValue)>0) pValueL[marker] <- pValue } } } all_pvalue[[trait]] <- pValueL } # 第二步:合并绘制所有性状的散点图 pdf('SingleMarkerAnalysis_ParW471_2021_10_21_combined.pdf') # 先绘制空白画布确定坐标轴范围 plot(x = as.numeric(map[2,]), y = rep(0, ncol(map)), type = "n", xlab = 'Chr 1B [cM]', ylab = '-log10(pValue)', ylim = c(0,7), main = "All traits single marker association") # 逐个添加不同性状的散点 for(i in 1:length(trait_names)){ pval <- all_pvalue[[trait_names[i]]] x_pos <- as.numeric(map[2, names(pval)]) y_val <- -log10(pval) points(x_pos, y_val, col = trait_colors[i], pch = 16) } # 添加图例,可调整cex参数缩放图例大小 legend("topright", legend = trait_names, col = trait_colors, pch = 16, cex = 0.8) dev.off()
内容的提问来源于stack exchange,提问作者Jamuzal
相关产品推荐
相关产品推荐

