Search code examples
rggplot2matrixdata-visualizationr-corrplot

How to color the background of a corrplot by group?


Consider this data, where we have several groups with 10 observations each, and we conduct a pairwise.t.test():

set.seed(123)
data <- data.frame(group = rep(letters[1:18], each = 10),
                   var = rnorm(180, mean = 2, sd = 5))
ttres <- pairwise.t.test(x=data$var, g=data$group, p.adjust.method = "none")#just to make sure i get some sigs for the example

Now lets get the matrix of p values, convert them to a binary matrix showing significant and non-significant values, and plot them with corrplot(), so that we can visualize which groups are different:

library(corrplot)
pmat <- as.matrix(ttres$p.value)
pmat<-round(pmat,2)
pmat <- +(pmat <= 0.1)
pmat
corrplot(pmat, insig = "blank", type = "lower")

enter image description here

Does anyone know a way to color the background of each square according to a grouping label? For instance, say we want the squares for groups a:g to be yellow, the squares for groups h:n to be blue, and the squares for groups o:r to be red. Or is there an alternative way to do this with ggplot?


Solution

  • You can pass a vector of background colors via the bg= parameter. The trick is just making sure they are in the right order. Here's on way to do that

    bgcolors <- matrix("white", nrow(pmat), ncol(pmat),dimnames = dimnames(pmat))
    bgcolors[1:6, ] <- "yellow"
    bgcolors[7:15, ] <- "blue"
    bgcolors[14:17, ] <- "red"
    bgcolors <- bgcolors[lower.tri(bgcolors, diag=TRUE)]
    corrplot(pmat, insig = "blank", type = "lower", bg=bgcolors)
    

    enter image description here

    Basically we just make a matrix the same shape as our input, then we set the colors we want for the different rows, and then we just pass the lower triangle of that matrix to the function.