Add color with a legend on row from pheatmap

2k Views Asked by At

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)
1

There are 1 best solutions below

2
On

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