Introduction
R package corrplot provides a visual exploratory tool on correlation matrix that supports automatic variable reordering to help detect hidden patterns among variables.
corrplot is very easy to use and provides a rich array of plotting options in visualization method, graphic layout, color, legend, text labels, etc. It also provides p-values and confidence intervals to help users determine the statistical significance of the correlations.
corrplot()
has about 50 parameters, however the mostly common ones are only a few. We can get a correlation matrix plot with only one line of code in most scenes.
The mostly using parameters include method
, type
, order
, diag
, and etc.
There are seven visualization methods (parameter method
) in corrplot package, named 'circle'
, 'square'
, 'ellipse'
, 'number'
, 'shade'
, 'color'
, 'pie'
. Color intensity of the glyph is proportional to the correlation coefficients by default color setting.
'circle'
and'square'
, the areas of circles or squares show the absolute value of corresponding correlation coefficients.'ellipse'
, the ellipses have their eccentricity parametrically scaled to the correlation value. It comes from D.J. Murdoch and E.D. Chow’s job, see in section References.'number'
, coefficients numbers with different color.'color'
, square of equal size with different color.'shade'
, similar to'color'
, but the negative coefficients glyphs are shaded. Method'pie'
and'shade'
come from Michael Friendly’s job.'pie'
, the circles are filled clockwise for positive values, anti-clockwise for negative values.
corrplot.mixed()
is a wrapped function for mixed visualization style, which can set the visual methods of lower and upper triangular separately.
There are three layout types (parameter type
): 'full'
, 'upper'
and 'lower'
.
The correlation matrix can be reordered according to the correlation matrix coefficients. This is important to identify the hidden structure and pattern in the matrix.
library(corrplot)
## corrplot 0.90 loaded
= cor(mtcars)
M corrplot(M, method = 'number') # colorful number
corrplot(M, method = 'color', order = 'alphabet')
corrplot(M) # by default, method = 'circle'
corrplot(M, order = 'AOE') # after 'AOE' reorder
corrplot(M, method = 'shade', order = 'AOE', diag = FALSE)
corrplot(M, method = 'square', order = 'FPC', type = 'lower', diag = FALSE)
corrplot(M, method = 'ellipse', order = 'AOE', type = 'upper')
corrplot.mixed(M, order = 'AOE')
corrplot.mixed(M, lower = 'shade', upper = 'pie', order = 'hclust')
Reorder a correlation matrix
The details of four order
algorithms, named 'AOE'
, 'FPC'
, 'hclust'
, 'alphabet'
are as following.
'AOE'
is for the angular order of the eigenvectors. It is calculated from the order of the angles \(a_i\),\[ a_i = \begin{cases} \arctan (e_{i2}/e_{i1}), & \text{if $e_{i1}>0$;} \newline \arctan (e_{i2}/e_{i1}) + \pi, & \text{otherwise.} \end{cases} \]
where \(e_1\) and \(e_2\) are the largest two eigenvalues of the correlation matrix. See Michael Friendly (2002) for details.
'FPC'
for the first principal component order.'hclust'
for hierarchical clustering order, and'hclust.method'
for the agglomeration method to be used.'hclust.method'
should be one of'ward'
,'single'
,'complete'
,'average'
,'mcquitty'
,'median'
or'centroid'
.'alphabet'
for alphabetical order.
You can also reorder the matrix ‘manually’ via function corrMatOrder()
.
If using 'hclust'
, corrplot()
can draw rectangles around the plot of correlation matrix based on the results of hierarchical clustering.
corrplot(M, order = 'hclust', addrect = 2)
corrplot(M, method = 'square', diag = FALSE, order = 'hclust',
addrect = 3, rect.col = 'blue', rect.lwd = 3, tl.pos = 'd')
R package seriation provides the infrastructure for ordering objects with an implementation of several seriation/sequencing/ordination techniques to reorder matrices, dissimilarity matrices, and dendrograms. For more information, see in section References.
We can reorder the matrix via seriation package and then corrplot it. Here are some examples.
library(seriation)
list_seriation_methods('matrix')
## [1] "BEA" "BEA_TSP" "Identity" "PCA" "PCA_angle" "Random"
list_seriation_methods('dist')
## [1] "ARSA" "BBURCG" "BBWRCG" "GW"
## [5] "GW_average" "GW_complete" "GW_single" "GW_ward"
## [9] "HC" "HC_average" "HC_complete" "HC_single"
## [13] "HC_ward" "Identity" "MDS" "MDS_angle"
## [17] "MDS_metric" "MDS_nonmetric" "OLO" "OLO_average"
## [21] "OLO_complete" "OLO_single" "OLO_ward" "QAP_2SUM"
## [25] "QAP_BAR" "QAP_Inertia" "QAP_LS" "R2E"
## [29] "Random" "SA" "Spectral" "Spectral_norm"
## [33] "SPIN_NH" "SPIN_STS" "TSP" "VAT"
data(Zoo)
= cor(Zoo[,-c(15, 17)])
Z
= function(corr, method, ...) {
dist2Order = as.dist(1 - corr)
d_corr = seriate(d_corr, method = method, ...)
s = get_order(s)
i return(i)
}
# PCA_angle, same as 'AOE' in corrplot() and corrMatOrder()
= get_order(seriate(Z, 'PCA_angle'))
i corrplot(Z[i, i], cl.pos = 'n')
# Hierarchical clustering
= dist2Order(Z, 'HC')
i corrplot(Z[i, i], cl.pos = 'n')
# Rank-two ellipse seriation
= dist2Order(Z, 'R2E')
i corrplot(Z[i, i], cl.pos = 'n')
# Spectral seriation
= dist2Order(Z, 'Spectral')
i corrplot(Z[i, i], cl.pos = 'n')
# TSP solver
= dist2Order(Z, 'TSP')
i corrplot(Z[i, i], cl.pos = 'n')
corrRect()
can add rectangles on the plot with three ways(parameter index
, name
and namesMat
) after corrplot()
. We can use pipe operator *>%
in package magrittr
with more convenience. Since R 4.1.0, |>
is supported without extra package.
library(magrittr)
# use index parameter
= get_order(seriate(Z, 'PCA_angle'))
i corrplot(Z[i, i], cl.pos = 'n') %>% corrRect(c(1, 9, 15))
# use name parameter
# Since R 4.1.0, the following one line code works:
# corrplot(M, order = 'AOE') |> corrRect(name = c('gear', 'wt', 'carb'))
corrplot(Z, order = 'AOE') %>%
corrRect(name = c('tail', 'airborne', 'venomous', 'predator'))
# use namesMat parameter
= rbind(c('eggs', 'catsize', 'airborne', 'milk'),
r c('catsize', 'eggs', 'milk', 'airborne'))
corrplot(Z, order = 'hclust') %>% corrRect(namesMat = r)
Change color spectra, color-legend and text-legend
The color of the correlation plots can be customized by col
. The function colorRampPalette()
is very convenient for generating color spectrum. Other option would be to use RcolorBrewer
package.
Parameters group cl.*
is for color-legend. The common-using are:
cl.pos
is for the position of color labels. It is character or logical. If character, it must be one of'r'
(means right, default iftype='upper'
or'full'
),'b'
(means bottom, default iftype='lower'
) or'n'
(means don’t draw color-label).cl.ratio
is to justify the width of color-legend, 0.1~0.2 is suggested.
Parameters group tl.*
is for text-legend. The common-using are:
tl.pos
is for the position of text labels. It is character or logical. If character, it must be one of'lt'
,'ld'
,'td'
,'d'
or'n'
.'lt'
(default iftype='full'
) means left and top,'ld'
(default iftype='lower'
) means left and diagonal,'td'
(default iftype='upper'
) means top and diagonal(near),'d'
means diagonal,'n'
means don’t add text-label.tl.cex
is for the size of text label (variable names).tl.srt
is for text label string rotation in degrees.
## diverging color example, suitable for matrix in [-N, N]
= colorRampPalette(c('#7F0000', 'red', '#FF7F00', 'yellow', 'white',
col1 'cyan', '#007FFF', 'blue', '#00007F'))
= colorRampPalette(c('red', 'white', 'blue'))
col2
library(RColorBrewer)
# use RcolorBrewer color
corrplot(M, order = 'AOE', addCoef.col = 'black', tl.pos = 'd',
cl.pos = 'n', col = brewer.pal(n = 10, name = 'PRGn'))
## bottom color legend, diagonal text legend, rotate text label
corrplot(M, order = 'AOE', cl.pos = 'b', tl.pos = 'd',
col = col1(10), diag = FALSE)
## text labels rotated 45 degrees and wider color legend with numbers right aligned
corrplot(M, type = 'lower', order = 'hclust', tl.col = 'black',
cl.ratio = 0.2, tl.srt = 45, col = col2(10))
## remove color legend, text legend and principal diagonal glyph
corrplot(M, order = 'AOE', cl.pos = 'n', tl.pos = 'n',
col = c('white', 'black'), bg = 'gold2')
Visualize non-correlation matrix, NA value and math label
We can visualize a non-correlation matrix by set is.corr=FALSE
, and assign colors by col.lim
. If the matrix have both positive and negative values, the matrix transformation keep every values positiveness and negativeness.
If your matrix is rectangular, you can adjust the aspect ratio with the win.asp
parameter to make the matrix rendered as a square.
## color example, suitable for matrix in [-N, 0] or [0, N]
= hcl.colors(10, "YlOrRd", rev = TRUE)
col3
= matrix(runif(80, 20, 30), 8)
N corrplot(N, is.corr = FALSE, col.lim = c(20, 30),
col = col3, cl.pos = 'b', win.asp = 0.8)
Notice: when is.corr=TRUE
, col.lim
only affect the color legend If you change it, the color on correlation matrix plot is still assigned on c(-1, 1)
# when is.corr=TRUE, col.lim only affect the color legend display
corrplot(M/2)
corrplot(M/2, col.lim=c(-0.5, 0.5))
By default, corrplot renders NA values as '?'
characters. Using na.label
parameter, it is possible to use a different value (max. two characters are supported).
Since version 0.78
, it is possible to use plotmath expression in variable names. To activate plotmath rendering, prefix your label with '$'
.
= M
M2 diag(M2) = NA
colnames(M2) = rep(c('$alpha+beta', '$alpha[0]', '$alpha[beta]'),
c(4, 4, 3))
rownames(M2) = rep(c('$Sigma[i]^n', '$sigma', '$alpha[0]^100', '$alpha[beta]'),
c(2, 4, 2, 3))
corrplot(10*abs(M2), col = col3, is.corr = FALSE,
col.lim = c(0, 10), tl.cex = 1.5)
Visualize p-value and confidence interval
corrplot()
can also visualize p-value and confidence interval on the correlation matrix plot. Here are some important parameters.
About p-value:
p.mat
is the p-value matrix, ifNULL
, parametersig.level
,insig, pch
,pch.col
,pch.cex
are invalid.sig.level
is significant level, with default value 0.05. If the p-value inp-mat
is bigger thansig.level
, then the corresponding correlation coefficient is regarded as insignificant. Ifinsig
is'label_sig'
,sig.level
can be an increasing vector of significance levels, in which casepch
will be used once for the highest p-value interval and multiple times (e.g.'*'
,'**'
,'***'
) for each lower p-value interval.insig
Character, specialized insignificant correlation coefficients,'pch'
(default),'p-value'
,'blank',
'n'
, or'label_sig'
. If'blank'
, wipe away the corresponding glyphs; if'p-value'
, add p-values the corresponding glyphs; if'pch'
, add characters (see pch for details) on corresponding glyphs; if'n'
, don’t take any measures; if'label_sig'
, mark significant correlations withpch
(seesig.level
).pch
is for adding character on the glyphs of insignificant correlation coefficients (only valid when insig is'pch'
). See?par
.
About confidence interval:
plotCI
is character for the method of plotting confidence interval. If'n'
, don’t plot confidence interval. If'rect'
, plot rectangles whose upper side means upper bound and lower side means lower bound respectively.lowCI.mat
is the matrix of the lower bound of confidence interval.uppCI.mat
is the Matrix of the upper bound of confidence interval.
We can get p-value matrix and confidence intervals matrix by cor.mtest()
which returns a list containing:
p
is the p-values matrix.lowCI
is the lower bound of confidence interval matrix.uppCI
is the lower bound of confidence interval matrix.
= cor.mtest(mtcars, conf.level = 0.95)
testRes
## specialized the insignificant value according to the significant level
corrplot(M, p.mat = testRes$p, sig.level = 0.10, order = 'hclust', addrect = 2)
## leave blank on no significant coefficient
corrplot(M, p.mat = testRes$p, method = 'circle', type = 'lower', insig='blank',
addCoef.col ='black', number.cex = 0.8, order = 'AOE', diag=FALSE)
## add p-values on no significant coefficients
corrplot(M, p.mat = testRes$p, insig = 'p-value')
## add all p-values
corrplot(M, p.mat = testRes$p, insig = 'p-value', sig.level = -1)
## add significant level stars
corrplot(M, p.mat = testRes$p, method = 'color', diag = FALSE, type = 'upper',
sig.level = c(0.001, 0.01, 0.05), pch.cex = 0.9,
insig = 'label_sig', pch.col = 'grey20', order = 'AOE')
## add significant level stars and cluster rectangles
corrplot(M, p.mat = testRes$p, tl.pos = 'd', order = 'hclust', addrect = 2,
insig = 'label_sig', sig.level = c(0.001, 0.01, 0.05),
pch.cex = 0.9, pch.col = 'grey20')
Visualize confidence interval.
# Visualize confidence interval
corrplot(M, lowCI = testRes$lowCI, uppCI = testRes$uppCI, order = 'hclust',
tl.pos = 'd', rect.col = 'navy', plotC = 'rect', cl.pos = 'n')
# Visualize confidence interval and cross the significant coefficients
corrplot(M, p.mat = testRes$p, lowCI = testRes$lowCI, uppCI = testRes$uppCI,
addrect = 3, rect.col = 'navy', plotC = 'rect', cl.pos = 'n')
References
Michael Friendly (2002). Corrgrams: Exploratory displays for correlation matrices. The American Statistician, 56, 316–324.
D.J. Murdoch, E.D. Chow (1996). A graphical display of large correlation matrices. The American Statistician, 50, 178–180.
Michael Hahsler, Christian Buchta and Kurt Hornik (2020). seriation: Infrastructure for Ordering Objects Using Seriation. R package version 1.2-9. https://CRAN.R-project.org/package=seriation
Hahsler M, Hornik K, Buchta C (2008). “Getting things in order: An introduction to the R package seriation.” Journal of Statistical Software, 25(3), 1-34. ISSN 1548-7660, doi: 10.18637/jss.v025.i03 (URL: https://doi.org/10.18637/jss.v025.i03), <URL: https://www.jstatsoft.org/v25/i03/>.