R – Heatmap color key with five different colors

heatmapr

I have the following code and not sure how to use it to display a heatmap with a color key displaying five different colors representing defined values:

hm <- heatmap.2(data_matrix, scale="none",Rowv=NA,Colv=NA,col = rev(brewer.pal(11,"RdBu")),margins=c(5,5),cexRow=0.5, cexCol=1.0,key=TRUE,keysize=1.5, trace="none")

Color key required:

<0.3 (blue)

0.3-1 (green)

1-1.3 (yellow)

1.3-3.0 (orange)

>3.0 (red)

I would be happy if someone can help. Thanks!

James

Best Answer

require(gplots)
require(RColorBrewer)

## Some fake data for you
data_matrix <- matrix(runif(100, 0, 3.5), 10, 10)

## The colors you specified.
myCol <- c("blue", "green", "yellow", "orange", "red")
## Defining breaks for the color scale
myBreaks <- c(0, .3, 1, 1.3, 3, 3.5)

hm <- heatmap.2(data_matrix, scale="none", Rowv=NA, Colv=NA,
                col = myCol, ## using your colors
                breaks = myBreaks, ## using your breaks
                dendrogram = "none",  ## to suppress warnings
                margins=c(5,5), cexRow=0.5, cexCol=1.0, key=TRUE, keysize=1.5,
                trace="none")

This should work, and give you some ideas of how to edit it further if you'd like. To get the legend with your exact values, I wouldn't bother with the built-in histogram and would instead just use legend:

hm <- heatmap.2(data_matrix, scale="none", Rowv=NA, Colv=NA,
                col = myCol, ## using your colors
                breaks = myBreaks, ## using your breaks
                dendrogram = "none",  ## to suppress warnings
                margins=c(5,5), cexRow=0.5, cexCol=1.0, key=FALSE,
                trace="none")
legend("left", fill = myCol,
    legend = c("0 to .3", "0.3 to 1", "1 to 1.3", "1.3 to 3", ">3"))
Related Topic