I am trying to plot a heatmap of a correlation matrix using ggplot2.
This is my correlation matrix
cormatx <- rcorr(as.matrix(data.frame))$r
I want to reorder the correlation matrix using correlation between variables as distance:
dist <- as.dist((1-cormatx)/2)
hcl <- hclust(dist)
cormatx1 <-cormatx[hcl$order, hcl$order]
So far so good. Now I reshape correlation matrix into long-format
melted_cormatx <- melt(cormatx1)
Now I try to plot:
Plot1 <- ggplot(melted_cormatx, aes(X1, X2)) +
geom_tile(aes(fill = value)) +
theme(panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank()) +
scale_fill_gradient2(limits=c(-.4, .4),
midpoint=0, low="navy", mid="white", high="red4", name="Scale") +
theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=1),
axis.title.x = element_blank(),
axis.title.y = element_blank()) +
theme(plot.title = element_text(size = rel(1)))
What I get is a heatmap with all variables in alphabetical order, not by correlation distance. What am I doing wrong???
Thank you.