Comments

Comment

Visitor
Avatar
This example does not work as presented. I have executed the code as written. Specifically, as written the upper triangular heat map does not correspond to the upper triangular matrix; shaded tiles appear on both sides of the diagonal.

Comment

Administrator
Avatar
You should use ggplot2 Ver. >= 1.0.0

Comment

Visitor
Avatar
Is there a way to remove the correlation of 1 on the diagonal?

Thanks.

Comment

Administrator
Avatar
To remove the diagonal values, just use the R code below:

Code R :
 
# Replace diagonal values by NA
diag(upper_tri) <- NA
 



The R code below can be use to compute and visualize the correlation matrix:


Code R :
 
# Helper function
# ++++++++++++++++++
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
  cormat[lower.tri(cormat)]<- NA
  return(cormat)
}
 
# Correl  tion matrix
# +++++++++++++++++++
mydata <- mtcars[, c(1,3,4,5,6,7)]
# Correlation matrix
cormat <- round(cor(mydata),2)
# Get upper triangle
upper_tri <- get_upper_tri(cormat)
# Replace diagonal values by NA
diag(upper_tri) <- NA
 
# Visualize the correlation matrix
# +++++++++++++++++
# Melt the correlation matrix
library(reshape2)
melted_cormat <- melt(upper_tri)
melted_cormat <- na.omit(melted_cormat)
 
# 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),
                       name="Pearson\nCorrelation") +
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                   size = 12, hjust = 1))+
  coord_fixed()
 





Good luck!!
AK