rdorlearn
rdorlearn

Reputation: 641

visualizing and revising a large number of plots in for loop in r

Here is the question where I have a number of plots and I want to revise them one by one visually at once pace.

xm <- matrix(runif(20000), ncol = 1000)

 for (i in 1:ncol(xm)){
    hist(xm[,i], col = i)
 }

This loop will make the plots so fast that I will have slit second to look (or not at all) in graphical device.

Upvotes: 2

Views: 417

Answers (1)

rdorlearn
rdorlearn

Reputation: 641

There can be several way around:

(1) look plots one by one - press return key to see next plot

We can create a breaks and user can use return key to see next plot.

xm <- matrix(runif(20000), ncol = 1000)
for (i in 1:ncol(xm)){
    hist(xm[,i], col = i, main = paste(i))
    grDevices::devAskNewPage(ask = TRUE)
}

Note that default behavior in R is grDevices::devAskNewPage(ask = FALSE).

(2) input plot number you want see from keyboard

You select which variable you want to plot, this way you can avoid chronological visualization of the plots, or else you can input the plot number(s) you want, in the order you want and click stop when you are done.

for (i in 1:ncol(xm)){ 
    i <- scan(nmax=1)
    hist(xm[,i], col = i, main = paste(i))
}

(3) all plots in new windows

If you would like to make a new plot each time, you can use:

for (i in 1:10){
    hist(xm[,i], col = i, main = paste(i))
    dev.new()
}

(4) multiple plot in single window

If you like to plot multiple plots in a single plot:

par(mfrow = c(5,2))
for (i in 1:10){
    hist(xm[,i], col = i, main = paste(i))
}

(5) Pdf file with multiple plots in separate page

Another way to save the files as PDF or other format:

The following will create output PDF will all figures in different page and then can scrolled down up.

pdf("outtrtt.pdf",width=7,height=5)
    for (i in 1:ncol(xm)){
        hist(xm[,i], col = i, main = paste(i))
    }
dev.off()

(6) separate pdf files per plot

Or if you want to create output as single PDF file per plot or other image file types this may do so. Please note that this may be different in mac and windows.

 for (i in 1:ncol(xm)){
     pdf(paste("var", i, ".pdf", sep = ""),width=7,height=5)
         hist(xm[,i], col = i, main = paste(i))
     dev.off()
 }

(7) separate image files

You can save as jpeg or other format of your choice

 for (i in 1:ncol(xm)){
     jpeg(paste("var", i, ".jpeg", sep = ""),width=700,height=500)
         hist(xm[,i], col = i, main = paste(i))
     dev.off()
 }

Other answers are welcome.

Upvotes: 5

Related Questions