Home > Back-end >  reorder x-axis with heatmap in R
reorder x-axis with heatmap in R

Time:03-23

I am used to using ggplot2, so I have only used fct_inorder() to reorder my axes. It should be Gate 0 - 3 then Full. How do you do this with a base function like heatmap? df and code below. Thank you!

Wizard_heatmap <- structure(list(Response = c("LIZARD", "LIZARD", "LIZARD", "NR", 
                                              "NR", "WAITER", "WEEKEND", "WHALE", "WHEELCHAIR", "WHIP", "WHISKEY", 
                                              "WHISTLE", "WHISTLE", "WHISTLE", "WIND", "WINDMILL", "WINDOW", 
                                              "WINDOW", "WINTER", "WISDOM", "WISDOM", "WIZARD", "WIZARD", "WIZARD", 
                                              "WIZARD", "WOMEN", "WOOD", "WOODCHIP"), 
                                 Target = c("WIZARD","WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", 
                                            "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD",
                                            "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", 
                                            "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD"), 
                                 Gate = c("Full", "Gate 2", "Gate 3", "Gate 0", "Gate 1", 
                                          "Gate 0", "Gate 1", "Gate 0", "Gate 0", "Gate 0", "Gate 1", 
                                          "Gate 0", "Gate 1", "Gate 2", "Gate 0", "Gate 0", "Gate 0", 
                                          "Gate 1", "Gate 0", "Gate 1", "Gate 2", "Full", "Gate 1", 
                                          "Gate 2", "Gate 3", "Gate 0", "Gate 0", "Gate 0"), 
                                 n = c(1, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 7, 
                                       1, 15, 1, 12, 14, 1, 1, 1)), row.names = c(NA, -28L), class = c("tbl_df", "tbl", "data.frame"))

heatmap(with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate)))))

CodePudding user response:

I wonder if, given your data, you are not interested in the dendrogram and are just looking for a standard heatmap? If do, then perhaps using ggplot would give you the control you need?

m <- with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate))))

for(i in seq(nrow(Wizard_heatmap))) {
  m[Wizard_heatmap$Response[i], Wizard_heatmap$Gate[i]] <- Wizard_heatmap$n[i]
}

df <- setNames(as.data.frame(as.table(m)), c("Response", "Gate", "n"))

library(ggplot2)

ggplot(df, aes(Gate, Response, fill = n))  
  geom_tile(color = "gray")  
  theme_minimal()  
  scale_fill_gradientn(colours = c("red4", "red", "orange", "yellow", "white"))

enter image description here

  • Related