0

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.

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Sophie
  • 11
  • 1
  • 6
  • 1
    try converting to a factor with the order you desire e.g. https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph?rq=1 – Jack Brookes May 07 '18 at 09:37
  • If you want answers, please provide a reproducible example so we can run the code ourselves to replicate the problem https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Jack Brookes May 07 '18 at 09:38

0 Answers0