Skip to content

Instantly share code, notes, and snippets.

@jokergoo
Last active June 8, 2020 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jokergoo/9b93c9741b372b8433481f4c46eeacae to your computer and use it in GitHub Desktop.
Save jokergoo/9b93c9741b372b8433481f4c46eeacae to your computer and use it in GitHub Desktop.
set.seed(123)
m = matrix(rnorm(100*10), nrow = 100)
# you should clustr the columns before making the heatmap because the column
# ordering will be used in `panel.fun`
column_hclust = hclust(dist(t(m)))
subgroup = sample(letters[1:3], 100, replace = TRUE, prob = c(1, 5, 10))
rg = range(m)
panel_fun = function(index, nm) {
pushViewport(viewport(xscale = c(0.5, ncol(m) + 0.5), yscale = rg))
grid.rect()
grid.yaxis(gp = gpar(fontsize = 8))
# `index` is the row order that has been reordered from hierarchical clustering,
# but we don't have this information for the columns, so the column order
# after clustering should be calculated in advance
m2 = m[index, column_hclust$order, drop = FALSE]
for(i in 1:ncol(m2)) {
grid.boxplot(m2[, i], pos = i)
}
popViewport()
}
anno = anno_zoom(align_to = subgroup, which = "row", panel_fun = panel_fun,
size = unit(2, "cm"), gap = unit(1, "cm"), width = unit(4, "cm"),
link_width = unit(1, "cm"))
# turn off `column_dend_reorder`, just to make sure the order of the `column_hclust`
# is the same as in the heatmap
Heatmap(m, name = "mat",
cluster_columns = column_hclust, column_dend_reorder = FALSE,
right_annotation = rowAnnotation(foo = anno), row_split = subgroup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment