Search code examples
rr-corrplot

Combined corrplot for data with two groups?


I wonder if I could generate a combined corrplot for two groups of data? That is to say, the upper triangular for one group, and the lower triangular for another group. I give an example as follows:

library(corrplot)

mydata <- replicate(5, rnorm(20))

colnames(mydata) <- c('x1','x2','x3','x4','x5')

mydata <- transform(mydata, group = c(rep('A',10),rep('B',10)))

corrplot(cor(mydata[which(mydata$group=='A'),c(1:5)]), method="number", type="upper", title="Group A", mar=c(1,0,1,0))
corrplot(cor(mydata[which(mydata$group=='B'),c(1:5)]), method="number", type="lower", title="Group B", mar=c(1,0,1,0))

Now in this example, the figures are as follows: enter image description hereenter image description here

It would be interesting to me if somebody could combine these two figures into one figure? Thanks in advance!


Solution

  • You could replace the values of one correlation matrix with the values from the other.

    cor_A <- cor(mydata[which(mydata$group=='A'),c(1:5)])
    cor_B <- cor(mydata[which(mydata$group=='B'),c(1:5)])
    
    # replace the values
    cor_A[lower.tri(cor_A)] <- cor_B[lower.tri(cor_B)]
    
    corrplot(cor_A, method="number", title="Group A & B", mar=c(1,0,1,0))
    

    enter image description here

    data

    set.seed(1)
    mydata <- replicate(5, rnorm(20))
    colnames(mydata) <- c('x1','x2','x3','x4','x5')
    mydata <- transform(mydata, group = c(rep('A',10),rep('B',10)))