Quick Correlation Heatmap in R

July 17, 2015

(This article was first published on r - Brandon Bertelsen, and kindly contributed to R-bloggers)

Quick Correlation Heatmap in R

Quick Correlation Heatmap in R

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(
  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") + 
    x = "", 
    y = "",
    fill = "Correlation") + 
  theme_grey() +
    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) {


     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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)