I'm trying to visualize correlation matrices using heatmaps. However, the results can be unsightly and seem unstructured. I give an example below (blue is positive correlation, red is negative).
How could I bring the high correlation entries closer to the diagonal? That is, how can I reduce the bandwith of a correlation matrix through reordering of the variables?
Reducing the bandwith of a symmetric matrix is an important problem in numerical linear algebra. From what I found (GPS and Cuthill-Mckee algorithms), they usually approach the problem by first transforming the correlating matrix to the adjacency matrix of a graph. However, I do not want to introduce an arbitrary cutoff for this procedure and I would prefer simpler approaches.
I tried re-ordering the variables by the sum of their squared correlation to each other (see below). It gives better-than-nothing results, but isn't quite nice enough.
Here's my code.
cor.im <- function(df) {
n = length(df)
m = cor(df)
image(x = 1:n, y = 1:n, z = m[,n:1], zlim = c(-1,1),
xlab = "", ylab = "",
col = colorRampPalette(
colors = c("red", "white", "blue")
)(256),
axes = F
)
text(x = 1:n, y=n:1, labels=names(df), col="white")
}