Search code examples
rr-corrplot

Print multiple corrplots (R) in the figure


I am working with corrplot and following example here Plotting multiple corrplots (R) in the same graph I can display multiple corrplots(R) in the same graph. However I would like to save to a tiff file and because I working with loop I don't know how to achieve this. See code below.

I loop through several block of my experiments (Block1, block2) and plot the corrplot one next to another. This works. I don't understand how to direct to tiff file. In particular where to put

tiff(file = 'Figure4Plots.tiff', width = 12, height = 12, units = "in", res = 300) and dev.off() I tried after dflist and several others but does not work Thanks!

dflist<-c('Block1', 'Block2') 

par(mfrow=c(2,2))

for (i in seq_along(dflist)) {
#Subset different Blocks
dataCorr<- subset(total , (block == dflist[i] ))

p.mat <- cor.mtest(dataCorr)
M<-cor(dataCorr)

col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot(M, method="color", col=col(200),  
       type="upper",  title = title,
       addCoef.col = "black", # Add coefficient of correlation
       tl.col="red", tl.srt=45, #Text label color and rotation
       # Combine with significance
       p.mat = p.mat, sig.level = 0.05, insig = "blank", 
       diag=TRUE,
      mar=c(0,0,1,0) )}

Solution

  • I don't have your original data, and I'm not familiar with the corrplot package, so I've made some dummy data and used just a simple plot() function. Unless there's something particular about the corrplot() function, you should be able to enclose most of your code in a tiff() block, like this:

    dflist <- c('Block1', 'Block2', 'Block3', 'Block4') 
    
    total <- data.frame(block=sample(dflist, size=100, replace=TRUE), x=runif(100), y=runif(100)*2)
    
    tiff(file = 'Figure4Plots.tiff', width = 12, height = 12, units = "cm", res = 72)
    
        par(mfrow=c(2,2))
    
        for (thisBlock in dflist) {
    
            #Subset different Blocks
            dataCorr <- subset(total , (block == thisBlock ))
            dataCorr <- dataCorr[, c('x', 'y')]
    
            plot(dataCorr)
        }
    
    dev.off()
    

    This code produces Figure4Plots.tiff:

    enter image description here