jokergoo / ComplexHeatmap

Make Complex Heatmaps
https://jokergoo.github.io/ComplexHeatmap-reference/book/
Other
1.31k stars 227 forks source link

columnAnnotation() is not working for adding column names #1027

Open chiwwong opened 1 year ago

chiwwong commented 1 year ago

I want to customize the column and row names of the heatmap. For some reason (because the real dataset comprises duplicated row/ column names which are not allowed by R), I need to add some prefixes to the row/ column names. However, I want to omit these prefixes when plotting the graph.

I think re-annotate the row names work perfectly using code

Heatmap(mat) +
  rowAnnotation(test = anno_text(gsub("[a-z]*", "", rownames(mat))))

I used the toy dataset at the beginning of chapter 2.

set.seed(123)
nr1 = 4; nr2 = 8; nr3 = 6; nr = nr1 + nr2 + nr3
nc1 = 6; nc2 = 8; nc3 = 10; nc = nc1 + nc2 + nc3
mat = cbind(rbind(matrix(rnorm(nr1*nc1, mean = 1,   sd = 0.5), nr = nr1),
          matrix(rnorm(nr2*nc1, mean = 0,   sd = 0.5), nr = nr2),
          matrix(rnorm(nr3*nc1, mean = 0,   sd = 0.5), nr = nr3)),
    rbind(matrix(rnorm(nr1*nc2, mean = 0,   sd = 0.5), nr = nr1),
          matrix(rnorm(nr2*nc2, mean = 1,   sd = 0.5), nr = nr2),
          matrix(rnorm(nr3*nc2, mean = 0,   sd = 0.5), nr = nr3)),
    rbind(matrix(rnorm(nr1*nc3, mean = 0.5, sd = 0.5), nr = nr1),
          matrix(rnorm(nr2*nc3, mean = 0.5, sd = 0.5), nr = nr2),
          matrix(rnorm(nr3*nc3, mean = 1,   sd = 0.5), nr = nr3))
   )
mat = mat[sample(nr, nr), sample(nc, nc)] # random shuffle rows and columns
rownames(mat) = paste0("row", seq_len(nr))
colnames(mat) = paste0("column", seq_len(nc))

However, I tried to use the columnAnnotation(), it always gave me an error message:

Heatmap(mat) +
  rowAnnotation(test = anno_text(gsub("[a-z]*", "", rownames(mat)))) +
  columnAnnotation(test = anno_text(gsub("[a-z]*", "", colnames(mat)), which = "column"))

Error: You should specify which = row or use rowAnnotation() directly if you want to add row annotations horizontally.

I have also tried several variants, but have had no luck.

Heatmap(mat) +
  rowAnnotation(test = anno_text(gsub("[a-z]*", "", rownames(mat)))) +
  HeatmapAnnotation(test = anno_text(gsub("[a-z]*", "", colnames(mat)), which = "column"))
Heatmap(mat) +
  rowAnnotation(test = anno_text(gsub("[a-z]*", "", rownames(mat)))) +
  columnAnnotation(test = anno_text(gsub("[a-z]*", "", colnames(mat))))
jokergoo commented 1 year ago

You cannot mix the use of rowAnnotation() and columnAnnotation(). You can do:

Heatmap(mat, bottom_annotation = columnAnnotation(test = anno_text(gsub("[a-z]*", "", colnames(mat))))) +
  rowAnnotation(test = anno_text(gsub("[a-z]*", "", rownames(mat))))

Or

Heatmap(mat,
  right_annotation = rowAnnotation(test = anno_text(gsub("[a-z]*", "", rownames(mat)))),
  bottom_annotation = columnAnnotation(test = anno_text(gsub("[a-z]*", "", colnames(mat)))))