bluepole
bluepole

Reputation: 345

Manipulations with corrplot

I want to manipulate the plotting from the R package corrplot. With the following example from the package:

library(corrplot)
data(mtcars)
M <- cor(mtcars)

cor.mtest <- function(mat, conf.level = 0.95){
  mat <- as.matrix(mat)
  n <- ncol(mat)
  p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n)
  diag(p.mat) <- 0
  diag(lowCI.mat) <- diag(uppCI.mat) <- 1
  for(i in 1:(n-1)){
    for(j in (i+1):n){
      tmp <- cor.test(mat[,i], mat[,j], conf.level = conf.level)
      p.mat[i,j] <- p.mat[j,i] <- tmp$p.value
      lowCI.mat[i,j] <- lowCI.mat[j,i] <- tmp$conf.int[1]
      uppCI.mat[i,j] <- uppCI.mat[j,i] <- tmp$conf.int[2]
    }
  }
  return(list(p.mat, lowCI.mat, uppCI.mat))
}
res1 <- cor.mtest(mtcars,0.95)

we can plot out the matrix with those statistically insignificant cells with a X sign:

corrplot(M, p.mat = res1[[1]], sig.level=0.05)

In addition, the confidence intervals can be shown with:

corrplot(M, low=res1[[2]], upp=res1[[3]], order="hclust",
              rect.col="navy", plotC="rect",cl.pos="n")

I'd like to combine the above two plots with the following manipulations:

1) Is it possible to paint the background of those statistically significant (instead of insignificant) cells with a color (e.g., deep blue)?

2) How to plot the lower triangular part of the matrix as 1) while using the upper triangular part to show the confidence intervals?

Upvotes: 1

Views: 962

Answers (1)

ani
ani

Reputation: 173

Regarding your 2nd question, you could plot the lower triangle:

corrplot(M, p.mat = res1[[1]], sig.level=0.05, 
        type='lower', tl.pos='lt')

and the upper one:

corrplot(M, low=res1[[2]], upp=res1[[3]], order="hclust",
        rect.col="navy", plotC="rect",cl.pos="n", 
        type='upper', tl.pos='n', add=T)

Regarding your 1st question, I'm not sure what you mean with background (I can't make comments yet - so I write here).

EDIT: One way to set the background color of each square according to its p-value is to give a matrix for bg. This works only for type="full". For a triangle part this has to be adjusted, otherwise the colors will be used from the part of the matrix that is not plotted.

sig_level = 0.05
bg_colors <- res1[[1]] < sig_level
bg_colors[bg_colors == T] <- "yellow"
bg_colors[bg_colors == F] <- "white"
diag(bg_colors) <- "white" # if the diagonal values shall be white

# select colors from lower/upper part of matrix:
bg_colors_lower <- bg_colors[lower.tri(bg_colors, diag=T)]
bg_colors_upper <- bg_colors[upper.tri(bg_colors, diag=T)]

# lower triangle
corrplot(M, p.mat = res1[[1]], sig.level=sig_level, 
         type='lower', tl.pos='lt', bg=bg_colors_lower)

# upper triangle
corrplot(M, low=res1[[2]], upp=res1[[3]], order="hclust",
         rect.col="navy", plotC="rect",cl.pos="n", 
         type='upper', tl.pos='n', add=T, bg=bg_colors_upper)

This gives:

Corrplot with adjusted background color and mixed type

Upvotes: 1

Related Questions