为条形图创建一个函数并在循环中调用它并保存所有图形

时间:2016-09-19 12:31:04

标签: r loops plot

我需要帮助才能在循环中对多个文件进行条形码处理。我创建了一个函数来条形图这些不同的文件,只有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,即使我在lablex中输入了“平均值”而在labley中输入了“ master id ”。 还告诉我如何用10个不同的名称保存这些不同的图表,例如plot1.jpg to plot10.jpg

2 个答案:

答案 0 :(得分:1)

这将创建十个单独地块的pdf文件

    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

答案 1 :(得分: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()
}