In corrplot()
, is it possible to visualize confidence intervals numerically below the coefficients?
library(corrplot)
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)
res2 <- cor.mtest(mtcars,0.99)
I would like to add to the following plot, low=res1[[2]]
and upp=res1[[3]]
confidence intervals as numbers below the correlation coefficients.
corrplot(M, method="number")
corrplot
is a pretty text text()
table. So we can try adding additional text on it.
Continuing from your example:
corrplot(cor(mtcars), method="number")
We form the confidence interval labels:
conf <- paste0("[", format(res1[[2]], digits=1), ":", format(res1[[3]], digits=1), "]")
And add them as text to the existing corrplot
:
xs <- row(res1[[1]])
ys <- (ncol(res1[[1]])+1) - col(res1[[1]])
text(xs, ys, conf, pos=1, cex=0.5)
NOTE: seems like y=1 starts on the top so we need to invert it (that's why ys
expression is more complicated than xs
.
Here is the result: