rggplot2

reorder heatmap


I found this case that resembles my issue, so I will use that other example to express my issue:

How to plot dataframe in R as a heatmap/grid?

I noticed that in the solution of this issue, the order is reverse alphabetical (tension, migraine NoAura, migraine Aura, cluster) instead of the original order (tension, cluster, migraine NoAura, migraine Aura).

What would I do, if I wanted a heatmap that uses the original order from the table it was based on?


Solution

  • To keep the order as in the original data you have to convert your variable to a factor with your desired order for which forcats::fct_inorder is handy:

    dt <- data.frame(
      tension = c(NA, 1.943113e+08, 8.462798e+00, 2.833333e+00),
      cluster = c(1.5, NA, NA, NA),
      migraineNoAura = c(6.960453e+00, NA, NA, 7.148313e+07),
      migraineAura = c(3.596953, NA, 7.499999, NA)
    )
    
    rownames(dt) <- c("tension", "cluster", "migraineNoAura", "migraineAura")
    
    library(tidyverse)
    
    dt2 <- dt |>
      rownames_to_column() |>
      mutate(rowname = fct_inorder(rowname)) |>
      pivot_longer(-rowname, names_to = "colname") |>
      mutate(colname = factor(colname, levels(rowname)))
    
    ggplot(dt2, aes(x = rowname, y = colname, fill = value)) +
      geom_tile()