(This article was first published on

**r - Brandon Bertelsen**, and kindly contributed to R-bloggers)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 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...