require(manipulate)
require(ggplot2)
require(reshape2)
 
# reads from MATLAB output by fieldtrip or ELEcro tab export
 
datatype="ELEcro"
#datatype=MATLAB
 
if (datatype=="ELEcro"){
  filename<-file.choose()
  sample_rate<-read.table(filename,skip=1,nrows=1)[1,1]
  data<-read.table(filename,col.names=c("ch1","ch2","ch3","ch4"),header=TRUE, skip=3)
  data$time<-as.numeric(rownames(data))/sample_rate*1000  # correct for sample rate  
} else
data<-read.csv(file.choose(),col.names=c("time","ch1","ch2","ch3","ch4"))
}
 
# use manipulate library to make an interactive plotter
 
manipulate({
 
  p <- ggplot() + ylab("level")
    if(ch1_on==TRUE) p<-p + geom_line(data=data, aes(time,ch1),colour="blue")
    if(ch2_on==TRUE) p<-p + geom_line(data=data, aes(time,ch2),colour="green")
    if(ch3_on==TRUE) p<-p + geom_line(data=data, aes(time,ch3),colour="orange")
    if(ch4_on==TRUE) p<-p + geom_line(data=data, aes(time,ch4),colour="red")
  p + xlim(x.min,x.max)
},
          ch1_on = checkbox(TRUE, "CH1"),
          ch2_on = checkbox(TRUE, "CH2"),
          ch3_on = checkbox(TRUE, "CH3"),
          ch4_on = checkbox(TRUE, "CH4"),
          x.min=slider(min(data$time),max(data$time),initial=min(data$time)), 
          x.max=slider(min(data$time),max(data$time),initial=max(data$time))
  )