Making multiple multi-line plots from one matrix

140 views Asked by At

I'm wondering if there's a way to combine the apply function along with the matplot function to generate a new plot for every n columns in a matrix.

I currently have a matrix with 1350 rows with 640 columns. I'm plotting the values for all the rows for every 8 columns using matplot:

png("cmpd1.png")
matplot(data[,1:8], type="l", y-lab="z-score", axes = F) 
axis(side=2)
dev.off()

I want to automate this a bit and have the column values shift by eight each loop and the label on the png to change by one. Can someone please give directions?

2

There are 2 answers

2
and-bri On BEST ANSWER

I think there is a version with lapply() but a loop does the job as well

for(i in seq(1,ncol(data),8)){
  png(paste0("cmpd",i,".png"))
  matplot(data[,i:(i+7)], type="l", ylab="z-score", axes = F) 
  axis(side=2)
  dev.off()
}
0
jnas On

Here is an answer with vapply() and formatted plot names. The closed device id will be returned.

data <- matrix(rnorm(100*128),nrow = 100,ncol = 128)
vapply(seq(from=1,to=ncol(data)-8,by=8), 
   FUN = function (x) {
     png(paste0("cmpd",formatC(width = 3, format = "d", flag="0", x=x%/%8),".png"))
     matplot(data[,x:(x+8)], type="l", ylab="z-score", axes = F) 
     invisible(dev.off())
     },
   FUN.VALUE=integer(1)
)