0

I create a heatmap, I would like to add color on the row with a legend

I got this :

enter image description here

I would like this a legend with color from only row data :

enter image description here

My code is :

library(pheatmap)
test = matrix(rnorm(200), 20, 10)
test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3
test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2
test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4
colnames(test) = paste("Test", 1:10, sep = "")
rownames(test) = paste("Gene", 1:20, sep = "")

# Draw heatmaps
pheatmap(test)
Julie Hardy
  • 127
  • 8

1 Answers1

0

The native supported way to annotate in pheatmap is using annotation_row, as below, which will add an annotation track to the left of the heatmap:

gene_annot <- data.frame(Experiment = rep(c("Exp1", "Exp2"), each = 10), 
                         row.names = rownames(test))
pheatmap(test, annotation_row = gene_annot)

enter image description here

However, if you want to have it the way you're proposing, you can do that using grid and gridExtra, which is a pretty manual process: make the heatmap, modify the gtable object directly, then make the legend, then add the legend to the table.

library(grid) library(gridExtra)

hm <- pheatmap(test, silent = TRUE)
hm$gtable$grobs[[5]]$gp$col <- rep(c("black", "red"), each = 10)
leg <- legendGrob(c("Exp1", "Exp2"), nrow = 2, pch = 15, gp = gpar(fontsize = 10, col = c("black", "red")))
hm2 <- arrangeGrob(hm$gtable, leg, ncol = 2, widths = c(5,1))
grid.draw(hm2)

enter image description here

csgroen
  • 2,511
  • 11
  • 28
  • Thank's for your answer, but I am looking for a not manual way. I would like an automatic way. The same method like the function color on ggplot2. – Julie Hardy Oct 01 '20 at 13:31
  • You could make the grid stuff automatic with a function. Or try `complex_heatmap`. Though to be honest, I think annotation tracks are a better idea than coloring the gene name – csgroen Oct 01 '20 at 13:39