Last active
March 8, 2017 19:29
-
-
Save josherrickson/871cd819e2caaeb36376e31a61550832 to your computer and use it in GitHub Desktop.
ggheatmap - Create a heatmap in ggplot2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(reshape2) | |
library(ggplot2) | |
#' Create a heatmap in ggplot2 | |
#' | |
#' @param data Data set | |
#' @param print.cors Default TRUE. Should the correlations be printed in each block of the heatmap? | |
#' @param reoder Default TRUE. Should the entries be re-ordered via clustering, similar to `heatmap`? | |
#' @param colors Default c("red", "white", "blue"). Vector of length three defining colors for correaltions (1, 0, -1). | |
#' | |
#' @import dplyr, reshape2, ggplot2 | |
#' @return A gg object. | |
ggheatmap <- function(data, print.cors = TRUE, reorder = TRUE, colors = c("red", "white", "blue")) { | |
stopifnot(all(colors %in% colors())) | |
stopifnot(length(colors) == 3) | |
newdata <- select_if(data, is.numeric) | |
if (reorder) { | |
newdata <- newdata[, unlist(as.dendrogram(hclust(dist(cor(newdata, use = "pair")))))] | |
} | |
newdata <- melt(cor(newdata, use = "pair")) | |
out <- ggplot(newdata, aes(x = Var1, y = Var2, fill = value)) + | |
geom_tile() + | |
scale_fill_gradient2(low = colors[3], high = colors[1], mid = colors[2], | |
midpoint = 0, limit = c(-1, 1), name = "Correlation") + | |
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), | |
axis.title.x = element_blank(), | |
axis.title.y = element_blank()) | |
if (print.cors) { | |
out <- out + geom_label(aes(label = round(value, 2))) | |
} | |
out | |
} | |
ggheatmap(iris, colors = c("green", "white", "orange")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment