Skip to content

Instantly share code, notes, and snippets.

@clairemcwhite
Last active January 6, 2020 19:44
Show Gist options
  • Save clairemcwhite/7683966b827d2f6f0a1f3cb15b69cd39 to your computer and use it in GitHub Desktop.
Save clairemcwhite/7683966b827d2f6f0a1f3cb15b69cd39 to your computer and use it in GitHub Desktop.
Clustered ggplot2 heatmap
library(tidyverse)
get_order <- function(df, distmethod = "pearson", hclustmethod = "average", output_ordername = "order"){
#Get the row ordering from a clustering
hr <- hclust(as.dist(1-cor(t(df), method=distmethod)), method=hclustmethod)
order <- data.frame(hr$labels[hr$order])
order$ordering <- rownames(order)
names(order) <- c("ID", output_ordername)
return(order)
}
mtcars[is.na(mtcars)] <- 0 # Not needed for mtcars
# Get correlation between all variables
mtcars_cor <- cor(mtcars, mtcars, method = "pearson")
# Cluster correlations, get clustered row/column order
corr_order <- get_order(mtcars_cor) %>%
as_tibble() %>%
mutate(ID = as.character(ID))
mtcars_cor %>%
as_tibble(rownames = "ID1") %>%
gather(ID2, r, -ID1) %>%
mutate(ID1 = fct_relevel(ID1, corr_order$ID)) %>% # Gets rows in clustered order
mutate(ID2 = fct_relevel(ID2, corr_order$ID)) %>% # Gets columns in clustered order
ggplot(aes(x= ID1, y = ID2, fill = r)) +
geom_tile() +
scale_fill_gradient(limit = c(0,1), low = "white", high = "black", name = "Pearson's r") +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1)) +
theme(axis.title.x = element_blank(), axis.title.y = element_blank())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment