vidya nair vidya nair - 2 months ago 5
R Question

create a function for barchart and call it in a loop and save all graphs

I need help to barplot multiple files in a loop. I have created a function to barplot these different files for only two columns out of 5 columns input file contains and then call the function

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)

}


output plot shows xlable as label1 and ylable as lable2, even though i have entered "average" in lablex and "master id" in labley.
Also tell me how to save these different plots with 10 diffrent names e.g. plot1.jpg to plot10.jpg

Answer

This will create a pdf file of your ten individual plots

   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" 


 i <- 1
  for (i in 1:10)
    {
    filename <- paste("C:/Users/admin/GoogleDrive/Vidya/R/document/Group_/",i,".csv",sep = "")
    group    <- read.csv(filename)
    jpeg(paste(i,".jpg"))
  bar.plot(group$total_pause_time,group$employee_id,label1,label2)
  dev.off()
  }

Sample plot