2017-06-26 39 views
1

我有兴趣从r中的多个文本文件(每个文件都有3列)绘制多个图。对于例如我有6个文本文件,其中V1(第一列的值)= 1循环绘制多个文件的多个图并保存在多个pdf文件中

1_d_a1_s.txt 
1_d_a2_s.txt 
1_d_a3_s.txt 
1_d_b1_s.txt 
1_d_b3_s.txt 
1_d_b3_s.txt 

和V1 = 2相同6个文件,V1 = 3,......,直到V1 = 10,从而总的I有60个文件。 V2(第2列)和V3(第3列)也有不同的范围。

我可以从1个数据集中绘制图形,但是如何为所有10个数据集(每个数据集包含6个文件)生成一个循环脚本并保存在相应的pdf中?

我的数据和1个数据集的脚本如下。请指导。 谢谢!

# my data (1_d_a1_s.txt) 
V1 V2 V3 
1 122 1 
1 123 1 
1 124 1 
1 132 2 
1 133 2 
1 134 3 
1 140 3 
1 141 2 
1 142 2 
1 143 4 
1 144 2 
1 145 10 

# my data (2_d_a1_s.txt) 
V1 V2 V3 
2 127 1 
2 128 1 
2 132 2 
2 133 3 
2 134 3 
2 140 3 
2 145 2 
2 142 2 
2 143 4 
2 144 2 
2 157 8 

# Rscript for plotting data from 1 dataset 
library(reshape2) 
1_a1 <- read.table("1_d_a1_s.txt", header=FALSE, sep ="\t") 
1_a2 <- read.table("1_d_a2_s.txt", header=FALSE, sep ="\t") 
1_a3 <- read.table("1_d_a3_s.txt", header=FALSE, sep ="\t") 
1_b1 <- read.table("1_d_b1_s.txt", header=FALSE, sep ="\t") 
1_b2 <- read.table("1_d_b2_s.txt", header=FALSE, sep ="\t") 
1_b3 <- read.table("1_d_b3_s.txt", header=FALSE, sep ="\t") 

1_a1_r <- rename(1_a1,c(V1="A", V2="B", V3="C")) 
1_a2_r <- rename(1_a2,c(V1="A", V2="B", V3="C")) 
1_a3_r <- rename(1_a3,c(V1="A", V2="B", V3="C")) 
1_b1_r <- rename(1_b1,c(V1="A", V2="B", V3="C")) 
1_b2_r <- rename(1_b2,c(V1="A", V2="B", V3="C")) 
1_b3_r <- rename(1_b3,c(V1="A", V2="B", V3="C")) 

pdf("1_d_s.pdf")   
plot(NULL, lwd=1, xlim=range(1_a1_r$B, 1_a2_r$B, 1_a3_r$B,1_b1_r$B, 1_b2_r$B, 1_b3_r$B), ylim=range(1_a1_r$C, 1_a2_r$C, 1_a3_r$C,1_b1_r$C, 1_b2_r$C, 1_b3_r$C), xlab="B", ylab = "C", main="1_d_s Plot", xaxt="n") 
axis(1, at = seq(0, 2000, by = 100), las = 2)       
lines(1_a1_r$B,1_a1_r$C, pch=1, col= 1, lwd=1) 
lines(1_a2_r$B,1_a2_r$C, pch=2, col= 2, lwd=1) 
lines(1_a3_r$B,1_a3_r$C, pch=3, col= 3, lwd=1) 
lines(1_b1_r$B,1_b1_r$C, pch=4, col= 4, lwd=1) 
lines(1_b2_r$B,1_b2_r$C, pch=5, col= 5, lwd=1) 
lines(1_b3_r$B,1_b3_r$C, pch=6, col= 6, lwd=1) 
legend("topright",c("a1","a2", "a3", "b1", "b2", "b3"),col=c(1, 2, 3, 4, 5, 6), lwd=1, cex=1.0, text.font=8) 
dev.off() 

回答

0

你的例子有点难以重现,这里有一个可能有帮助的通用模板。

基本上你把每组文件放在一个目录下。迭代每个目录和每个位于其中的文件。

#getwd() 
for(i in 1:10){ 
    dir.create(path = paste0('dir',i),) 
    setwd(paste0('dir',i)) 
    for(j in 1:6){ 
    df <- data.frame(V1 = 1, V2 = 2, V3 = 3) 
    write.table(df, file = paste0('file',j,'.txt')) 
    } 
    setwd('..') 
} 


d <- list.dirs(path = getwd(), full.names = T) 
d <- d[grepl(x = d,'dir')] 

for(i in d){ 
    setwd(i) 
    pdf('helloworld.pdf') 
    plot(0, type = 'n', xlim = c(-10,10), ylim = c(-10,10)) 
    f <- list.files(i, pattern = 'txt') 
    for(j in f){ 
    df <- read.table(j) 
    points(df[,1],df[,2]) 
    } 
    dev.off() 
    setwd('..') 
}