This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Heatmap by group in R

Dear colleagues, Could you clarify please how to make such a figure with the help of ggplot2? I saw a similar solution, but I don't understand how to properly reorder columns and rows... I created a test table.

Group   Name    Sample1 Sample2 Sample3
A   Sub 200 500 600
A   Res 50  54  20
A   Gold    42  22  250
A   Fish    35  31  300 
A   Can 12  12  264
B   Zup 500 456 14
B   Reber   200 57  521
B   Hr  55  200 222
B   Teb 22  42  34
B   Zn  13  11  20
B   Kto 1   25  46
C   Ul  510 36  216
C   Fana    300 25  300
C   Ee  50  222 54

enter image description here

df1 = data.frame(ID = paste0("I", 1:40),
                 group = rep(c("Dry", "Rain"), each = 20),
                 subgroup = rep(paste0("S", 1:4), each = 10),
                 setNames(data.frame(replicate(8, rnorm(40))), letters[1:8]))
library(reshape2)
df1 = melt(df1, id.vars = c("ID", "group", "subgroup"))
df1 = df1[order(df1$group, df1$subgroup),]
df1$fact = paste(df1$subgroup, df1$ID)
df1$fact = factor(df1$fact, levels = unique(df1$fact))

ggplot(df1, aes(x = variable, y = fact, fill = value)) +
geom_tile() +
facet_grid(subgroup~., scales="free_y") +
theme(axis.text.y = element_blank())
ggplot2 r heatmap

You can also do this in ComplexHeatmap with the row_split and cluster_row_slices arguments, with the benefit of built-in clustering as is standard for most heatmaps in biology.

1 answer

Found the answer. Might be useful to someone.

https://jcoliver.github.io/learn-r/006-heatmaps.html

Log in to answer this question.