Site icon R-bloggers

Quick Correlation Heatmap in R

[This article was first published on r - Brandon Bertelsen, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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
   ])

To leave a comment for the author, please follow the link and comment on their blog: r - Brandon Bertelsen.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.