r – Reorder and split the ggplot heatmap based on the clusters in one of the columns

I generated a heatmap with ggplot, and order the samples by using hclust, However, I still need more reordering to get all the similar values corespondent with one of the samples in the ordered cluster. Here I generate a samples data to explain better.

set.seed(99)
M <- data.frame(names = paste0("g", seq(1,30)), S1 = runif(30, 0 , 8), S2 = runif(30, -4, 5), S3 = runif(30, -5, 5))

M.mat <- M %>% 
  tibble::column_to_rownames('names') %>% 
  as.matrix()
M.dendro <- as.dendrogram(hclust(d = dist(x = M.mat)))
dendro.plot <- ggdendrogram(data = M.dendro, rotate = TRUE) + 
  theme(axis.text.y = element_text(size = 6))
print(dendro.plot)
str(M.dendro)


dend.order <- order.dendrogram(M.dendro)

df <- melt(M, id.vars = "names")
df$names <- factor(x = df$names,
                    levels = M$names[dend.order], 
                    ordered = TRUE)
ggplot(df, aes(x = names, y = variable, fill = value)) +
  geom_tile(color = "black") +
  scale_fill_gradient2(low = muted("steelblue"), mid = "white", high = muted("red3"), 
                       midpoint = 0, space = "Lab", na.value = "grey50", 
                       guide = "colourbar", aesthetics = "fill"
  ) +
  theme(axis.text.x = element_text(angle = 90, hjust=1), legend.key.size = unit(0.4, "cm")) + 
  coord_fixed() 

For the generated heatmap, I need reorder it such that all the dark blue be on the bottom, the middle color and then the red on the top based on samples S3. Thank you enter image description here

Read more here: Source link