Is it possible to change the order of columns in heatmaply?

690 views Asked by At

I have created a dendrogram with heatmaply with a dendrogram object from the dendextend package. I was wondering if there is a way to change the order of the columns: vs, am, carb, wt, drat, gear, etc. For example, I want to sort them alphabetically. Is this possible?

library(heatmaply)
library(tidyverse)
library(RColorBrewer)
library(dendextend)

custom_colors <- c("#B6E2D3", "#887BB0", "#FFD53D", "#EF7C8E", "#A1F7A1", "#EFE7BC", "#C26DBC", "#14C2DD",
                   "#5CD85A", "#AB6B51", "#39918C", "#FFA384", "#57DDF3", "#D0B49F", "#EEB5EB", "#74BDCB")

dend_example <- mtcars %>% dist %>% hclust(method = "ward.D2") %>% 
  as.dendrogram %>% color_branches(k=5) %>% color_labels

heatmaply_mtcars<- heatmaply(mtcars, hclustfun = hclust, hclust_method = "ward.D2",
                             Rowv = dend_example, 
                             main = "mtcars",
                             show_dendrogram = c(TRUE, FALSE),
                             showticklabels = c(TRUE, TRUE),
                             scale_fill_gradient_fun = ggplot2::scale_fill_gradient2(high = "#025492"),
                             file = "heatmaply_mtcars.html",
                             column_text_angle = 30,
                             colorbar_thickness = 50)

enter image description here

1

There are 1 answers

0
Sara Altamirano On

I included a column dendrogram within heatmaply with the colv argument. The column dendrogram was rotated with the rotate function from the package dendextend:

dend_example <- mtcars %>% dist %>% hclust(method = "ward.D2") %>% 
  as.dendrogram %>% color_branches(k=5) %>% color_labels

column_dend <- t(mtcars) %>% dist %>% hclust(method = "ward.D2") %>% 
  as.dendrogram
column_dend  <- column_dend %>% rotate(c(vector_with_labels))

heatmaply_mtcars<- heatmaply(mtcars, hclustfun = hclust, hclust_method = "ward.D2",
                             Rowv = dend_example, 
                             Colv = column_dend,
                             main = "mtcars",
                             show_dendrogram = c(TRUE, FALSE),
                             showticklabels = c(TRUE, TRUE),
                             scale_fill_gradient_fun = ggplot2::scale_fill_gradient2(high = "#025492"),
                             file = "heatmaply_mtcars.html",
                             column_text_angle = 30,
                             colorbar_thickness = 50)