rheatmap

How to show legend in heatmap?


The problem is actually quite simple, yet I am not able to find a solution to it.

How to plot a heatmap and its legend, i.e. a bar with the color scale representing the minimum and the maximum value that are plotted?

I read the help of the heatmap() function, and using base R as explained here: r-graph-gallery.com heatmaps

This is what I'm doing:

heatmap(as.matrix(dataSet[, -1]), Colv = NA, Rowv = NA,
        scale="column", xlab="something", ylab="", main="A title",
        labRow=dataSet$labels, labCol=colnames(dataSet[, -1]),
        col= colorRampPalette(brewer.pal(8, "Oranges"))(25))

...and it works perfectly, but still I would like to plot a legend. Is there a way to do that?

This is a sample of the dataset which I'm working with. The first row is the header.

labels  6   1   4   8   3   2   9   7   5
aaa1    2   2   11  0   0   0   0   0   0
aaa2    3   3   16  0   0   0   0   0   0
aaa3    1   4   15  0   0   0   0   0   0
aaa4    1   6   17  0   0   0   0   0   4
aaa10   1   2   16  0   0   0   0   0   0
bbb11   1   0   2   0   1   2   1   0   0
bbb12   0   1   10  1   0   1   2   3   0
bbb13   1   0   0   0   2   0   0   0   0

Solution

  • You need to add the legend function as a separate line.

    library(RColorBrewer)
    
    dataSet<-read.table(header=TRUE, text="labels  6   1   4   8   3   2   9   7   5
    aaa1    2   2   11  0   0   0   0   0   0
    aaa2    3   3   16  0   0   0   0   0   0
    aaa3    1   4   15  0   0   0   0   0   0
    aaa4    1   6   17  0   0   0   0   0   4
    aaa10   1   2   16  0   0   0   0   0   0
    bbb11   1   0   2   0   1   2   1   0   0
    bbb12   0   1   10  1   0   1   2   3   0
    bbb13   1   0   0   0   2   0   0   0   0")
    
    heatmap(as.matrix(dataSet[, -1]), Colv = NA, Rowv = NA, 
            scale="column", xlab="something", ylab="", main="A title", 
            labRow=dataSet$labels, labCol=colnames(dataSet[, -1]), 
            col= colorRampPalette(brewer.pal(8, "Oranges"))(25))
    
    legend(x="bottomright", legend=c("min", "ave", "max"), 
         fill=colorRampPalette(brewer.pal(8, "Oranges"))(3))
    

    enter image description here

    Since you are scaling by the column, I am not sure what the expected range should be. In the example above, I assumed 3 levels in the legend. For better placement of the legend, you can adjust the x option or specify a x and y coordinate. See ?legend for more details.