Search code examples
rr-corrplot

R - corrplot - looking for a way to visually distinguish groups of columns


The following code:

Dat = read.table(text="varA1 varA2 varA3  varB1  varB2 varC1 varC2 varC3
             .01   .01  .35    .05    .06   .01   .01  .25
             .02   .21  .31    .34    .06  .04   .01  .35
             .01   .03  .35    .05    .03  .05   .31  .33
             .45   .01  .32    .08    .26  .11   .04  .35
             .01   .01  .35    .05    .03  .01   .33  .25",
             header=TRUE)

library(corrplot)
corrplot(as.matrix(Dat), is.corr=FALSE, tl.srt=45)

Creates this plot:

enter image description here

Is it possible to update the code to highlight the fact that I have three groups of variables, namely

  • varA1, varA2, varA3
  • varB1, varB2
  • varC1, varC2, varC3

So either putting a rectangle around all three (similar to the option hclust within corrplot, which unfortunately does not allow custom rectangles), like I did here using paint:

enter image description here

Or perhaps by printing the headers in three different colors, or any other way that I could visually distinguish the three groups of variables? Any tips are welcome, many thanks!


Solution

  • You can just use segments to draw in the borders.

    segments(c(0.5,3.5,5.5,8.5), rep(0.5,4), 
        c(0.5,3.5,5.5,8.5), rep(5.5,4), lwd=3)
    segments(c(0.5, 0.5), c(0.5, 5.5), c(8.5, 8.5), c(0.5,5.5), lwd=3)
    

    Corrplot with borders

    OR you can outline and fill in the background with different colors

    ColorScheme = c("#FFEEEE", "#EEFFEE", "#EEEEFF")
    Groups = c(rep(1,15), rep(2,10), rep(3, 15))
    corrplot(as.matrix(Dat), is.corr=FALSE, tl.srt=45, bg=ColorScheme[Groups])
    
    segments(c(0.5,3.5,5.5,8.5), rep(0.5,4), 
        c(0.5,3.5,5.5,8.5), rep(5.5,4), lwd=3)
    segments(c(0.5, 0.5), c(0.5, 5.5), c(8.5, 8.5), c(0.5,5.5), lwd=3)
    

    Colored corrplot