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
:
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:
But I couldn't get it.