Skip to content

Instantly share code, notes, and snippets.

@slavailn
Created July 10, 2020 00:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slavailn/16c77cf912e25aa97de4fba38fe44939 to your computer and use it in GitHub Desktop.
Save slavailn/16c77cf912e25aa97de4fba38fe44939 to your computer and use it in GitHub Desktop.
How to attach a side bar with cluster labels to a heatmap (pheatmap). Just a little snippet.
library(pheatmap)
# We need to use cutree inside pheatmap()
# functio, capture the returned object into a variable,
# and than extract the tree, cut it again to the same
# number of clusters and reorder.
# Resulting vector is converted to factor and used in the annotation data frame
# to create cluster labels
x <- some_matrix # matrix to cluster and show as a heatmap
annot_df <- some_annotation_data_frame # annotation data frame (optional)
out <- pheatmap(x, cluster_rows = T, cluster_cols = F,
clustering_method = "mcquitty", clustering_distance_cols = "euclidean",
clustering_distance_rows = "euclidean",
show_rownames = T,
annotation_col = annot_df, scale = "row", show_colnames = F,
cutree_rows = 4)
clusters <- cutree(out$tree_row, k=4)[out$tree_row[["order"]]]
annot_row <- data.frame(row.names = names(clusters),
cluster = as.factor(clusters))
pheatmap(clr_diff, cluster_rows = T, cluster_cols = F,
clustering_method = "mcquitty",
clustering_distance_rows = "euclidean",
show_rownames = T,
annotation_col = annot_df, scale = "row", show_colnames = F,
cutree_rows = 4, annotation_row = annot_row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment