Quick Correlation Heatmap in R

July 17, 2015 in #r #analysis #visualization

Correlation heatmap diamonds dataset

I find myself remaking this plot over and over. So here's a quick function. Also tests correlation significance. I quite like the spectral palette for the purpose of a heat map. It's not too painful on the eyes and variation is immediately identifiable.

#' Create a Heatmap
#' 
#' Function creates a correlation heatmap using ggplot2 given a data.frame
#' 
#' @param df A data.frame containing only numeric data
#' @param data.only Logical, if TRUE returns correlation and pvalue.

heatmap <- function(df, data.only = FALSE) {  
  require(ggplot2) # ggplot2
  require(reshape2) # melt
  test <- melt(cor(df,use = "na.or.complete"))
  listing <- list()
  for(x in 1:nrow(test)) {
    listing[[x]] <- round(
      cor.test(
        df[[test[x,1]]],
        df[[test[x,2]]])$p.value,3
      )
  }
  test$Test <- unlist(listing)
  p1 <- ggplot(test, aes(Var1,Var2,fill = value, label = round(value,2))) + 
  geom_tile() + 
  geom_text() +
  scale_fill_distiller(palette = "Spectral", trans = "reverse") + 
  labs(
    x = "", 
    y = "",
    fill = "Correlation") + 
  theme_grey() +
  theme(
    axis.text.x = element_text(angle = 25, size = 12),
    axis.text.y = element_text(size = 12),
    plot.background = element_blank(),
    axis.ticks.x = element_blank(),
    axis.ticks.y = element_blank(),
    panel.background = element_blank()
  )
  if(data.only) {
     return(test)
  }
  print(p1)
}

Usage:

heatmap(  
   diamonds[
     sapply(diamonds, is.numeric) # only numeric columns
   ])