0

I want to create a correlation heatmap matrix. I followed this tutorial. Here is the code:

mydata <- mtcars[, c(1,3,4,5,6,7)]

cormat <- round(cor(mydata),2)

# Get upper triangle of the correlation matrix
get_lower_tri <- function(cormat){
  cormat[upper.tri(cormat)]<- NA
  return(cormat)
}

lower_tri <- get_lower_tri(cormat)

library(reshape2)
melted_cormat <- melt(lower_tri, na.rm = TRUE)

# Heatmap
library(ggplot2)
ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+
  geom_tile(color = "white")+
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       midpoint = 0, limit = c(-1,1), space = "Lab", 
                       name="Pearson\nCorrelation") +
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                   size = 12, hjust = 1))+
  coord_fixed()

The problem is that ggplot changes the order of rows. Actually, here is the lower triangle of the matrix:

> lower_tri
       mpg  disp    hp  drat    wt qsec
mpg   1.00    NA    NA    NA    NA   NA
disp -0.85  1.00    NA    NA    NA   NA
hp   -0.78  0.79  1.00    NA    NA   NA
drat  0.68 -0.71 -0.45  1.00    NA   NA
wt   -0.87  0.89  0.66 -0.71  1.00   NA
qsec  0.42 -0.43 -0.71  0.09 -0.17    1

For example, the first row is mpg, but the first row of the heatmap is qsec: enter image description here

I want to get the structure of the heatmap exactly similar to the lower_tri matrix, i.e., the desired plot is something like this: enter image description here

But I couldn't get it.

Patris
  • 167
  • 2
  • 11

1 Answers1

1

In the image presented, the Var1 axis is going the correct way according to convention (1 at the bottom, 6 at the top). It just doesn't look right in the context of this matrix.

There's a simple fix though: you just reverse the factor levels in your Var1 column in melted_cormat

ggplot(
    data = melted_cormat,
    aes(Var2, forcats::fct_rev(Var1), fill = value)
  ) +
  geom_tile(color = "white") +
  scale_fill_gradient2(
    low = "blue", high = "red", mid = "white", midpoint = 0,
    limit = c(-1,1), space = "Lab", name="Pearson\nCorrelation"
  ) +
  theme_minimal() + 
  theme(
    axis.text.x = element_text(
      angle = 45, vjust = 1, size = 12, hjust = 1)
  ) +
  coord_fixed()

[I was hoping that scale_y_reverse might fix this, but it fails for factors]

Russ Hyde
  • 2,154
  • 12
  • 21