2016-09-19 32 views
1

我需要幫助來在一個循環中對多個文件進行barplot。我創建了一個功能barplot只有兩列,這些不同的文件從5列輸入文件中包含的,然後調用函數爲條形圖創建一個函數並在循環中調用它並保存所有圖形

bar.plot <- function(col_name1, col_name2,input_file, lable1, lable2) 

{ 

    barplot(col_name1,names.arg = col_name2, xlab = "label1", ylab = "lable2", 
col= "blue",main = "bar plot of average",border = "red") 

    box() 

    } 

#call the function for 10 files 
    i <- 1 

    for (i in 1:10) 
    { 

    filename <_paste("C:/Users/admin/GoogleDrive/Vidya/R/document/Group_",i,".csv",sep = "") 
    group <- read.csv(filename) 


    lablex <- "average" 

    labley <- "master id" 

    bar.plot(group$total_pause_time,group$employee_id, group, lablex, labley) 

    } 

輸出曲線顯示xlable作爲label1和ylable爲lable2,即使我已經進入了「 average「in lablex and」master id「in labley。 也告訴我如何用10個不同的名字保存這些不同的地塊,例如plot1.jpg到plot10.jpg

回答

1

這將創建十個單獨地塊

bar.plot <- function(col_name1, col_name2,input_file, lable1, lable2) 
{ 
    barplot(col_name1,names.arg = col_name2,xlab=label1,ylab=label2, 
col= "blue",main = "bar plot of average",border = "red") 
    box() 
    } 

#call the function for 10 files 
label1 <- "average" 
label2 <- "master id" 

setwd("C:/Users/admin/GoogleDrive/Vidya/R/document/Group_/") 
filename <- list.files(pattern = ".csv") 
myfiles <- lapply(filename, read.csv) 

    for (i in myfiles) 
    { 
    group <- data.frame(myfiles[i]) 
    jpeg(paste(i,".jpg")) 
    bar.plot(group$total_pause_time,group$employee_id,label1,label2) 
    dev.off() 
    } 

Sample plot

+0

嗨,這段代碼保存所有繪圖在一個pdf中,但仍然標籤不來作爲「平均」和「主ID」 –

+0

@vidyanair希望這可能對你有幫助 –

+0

kumar ok ..我會嘗試 –

0

試試這個:

bar.plot <- function(col_name1, col_name2,input_file, lable1, lable2) { 
barplot(col_name1,names.arg = col_name2, xlab = lable1, ylab = lable2, 
col= "blue",main = "bar plot of average",border = "red") 
box() 
} 

#call the function for 10 files 
for (i in 1:10){ 
filename <-paste("C:/Users/admin/GoogleDrive/Vidya/R/document/Group_",i,".csv",sep = "") 
    group <- read.csv(filename) 
lable1 <- "average" 
lable2 <- "master id" 
bar.plot(group$total_pause_time,group$employee_id, group, lable1, lable2) 
dev.copy(jpg,paste("C:/Users/admin/GoogleDrive/Vidya/R/document/plot",i,".jpg) 
dev.off() 
} 
+0

沒有working..still顯示lable1的PDF文件和lable2,而不是「平均」和「主ID」..和JPG不保存.. –

+0

如果這些文件,組1到組10已經顯示在全球環境,那麼就沒有必要讀取.csv ..在這種情況下如何做到這一點..意味着我直接想要從全球環境中導入這些文件同時增加他們的名字lfom group1到group10 –