1 # R script showing .pdf file with plots of all injection histograms for a certain file
3 # Can be called from the command line with:
4 # Rscript $this_script.R inputfile
12 # Functions for arranging multiple plots
13 vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
14 arrange_ggplot2 <- function(list, nrow=NULL, ncol=NULL, as.table=FALSE) {
16 if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
17 if(is.null(nrow)) { nrow = ceiling(n/ncol)}
18 if(is.null(ncol)) { ncol = ceiling(n/nrow)}
19 ## NOTE see n2mfrow in grDevices for possible alternative
21 pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
23 for(ii.row in seq(1, nrow)){
24 ii.table.row <- ii.row
25 if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
26 for(ii.col in seq(1, ncol)){
29 print(list[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
37 # Reading command line argument with the input file path
38 args <- commandArgs(trailingOnly = TRUE)
39 fp <- file(args[1], open = "r")
44 # Reading histograms one by one, line by line
45 while (length(oneLine <- readLines(fp, n = 1, warn = FALSE)) > 0)
46 { myVector <- (strsplit(oneLine, "\t"))
48 dfl <- ldply (myVector, data.frame)
50 name<-as.character(dfl[1,])
51 nbins<-as.numeric(as.character(dfl[4,]))
52 allbreaks<-as.numeric(as.character(dfl[5:(5+nbins-1),]))
54 dh<-data.frame(Name=as.character(dfl[1,]), Total=as.numeric(as.character(dfl[2,])), Mean=as.numeric(as.character(dfl[3,])), Nbins=as.numeric(as.character(dfl[4,])))
55 dh<-cbind(dh,Bstart=allbreaks[-length(allbreaks)])
56 dh<-cbind(dh,Bend=allbreaks[-1])
57 dh<-cbind(dh,Density=as.numeric(as.character(dfl[(5+nbins):(5+nbins*2-2),])))
59 # Plotting single histogram, if it only has one value then use geom_bar
61 plots[[i]]<-ggplot(data=data.frame(dh), aes(xmin=Bstart, xmax=Bend, ymin=0, ymax=Density)) + geom_rect(aes(fill=Density)) + theme_bw() + scale_x_continuous("Time [s]", allbreaks) + labs(title=name, y=element_text("Density %"))
63 plots[[i]]<-ggplot(data=data.frame(dh), aes(factor(Bstart))) + geom_bar(aes(fill=Density)) + theme_bw() + labs(title=name, y=element_text("Density %"), x=element_text("Time [s]"))
68 # Printing all plots together in a table
69 arrange_ggplot2(plots, as.table=TRUE)
72 write("Done producing a histogram plot. Open Rplots.pdf located in this folder to see the results", stdout())