Search code examples
rggplot2heatmaprescale

Scaling heat map colours for multiple heat maps


So I have a bunch of matrices that I am trying to plot as a heatmaps. I am using the heatmap.2() function in the ggplot2 packaage.

I have been trying for quite some time with it, and I am sure there is a very simple fix, but my issue is this:

How do I keep the colours consistent between heatmaps? For example, to make the values that provide the colours absolute as opposed to relative.

I have tried doing something similar to this question:

R/ggplot: Reuse color key for multiple heat maps

But I was unable to figure out the ggplot function; I kept receiving an error message stating that there were "no layers in plot".

After reading the comments on the above question, I tried using scales::rescale() and discrete_scale() but the former does not remove the problem, while the latter did not work.

I am fully aware that I might be doing something very simple wrong, and just being a bit of an idiot, but for the life of me I can't figure out where I am going wrong.

As for the data itself, I am trying to plot 10 matrices/heatmaps, each 10x10 cells (showing change over time) and the values in the cells range from 1.0 to 1.2.

As an example, this is the code I am using (once I have my 10x10 matrix).

Matrix1<-matrix(data=(runif(100,1.0,1.2)),nrow=10,ncol=10)
heatmap.2(Matrix1, Colv=NA, Rowv=NA, dendrogram="none",
    trace="none", key=F, cellnote=round(Matrix1,digits=2),
    notecex=1.6, notecol="black",
    labRow=seq(10,100,10), labCol=seq(10,100,10),
    main="Title1", xlab="Xlab1", ylab="Ylab1"
 )

So any help with either figuring out how to create the scaled values for the heatmap.2() function, or how I can use the ggplot() function would be greatly appreciated!


Solution

  • It's important to note that heatmap.2 is not a ggplot2 function. The ggplot2 package is not necessarily compatible with all plotting types. If you look at the ?heatmap.2 help page, in the upper left corner it shows you where the function is from. heatmap.2 {gplots} means that function comes from the gplots package. These are different pacakges so they have different rules how they work.

    To get the same colors across different heatmaps, you want to explicitly get the breaks= parameter. By default it splits the observed range of the data into equal chunks. But since each data set may have a different min and max, these chunks may have different start and end points. By specifying breaks, you can make them all consistent. Since your data ranges from 1 to 1.2, you can set

    mybreaks <- seq(1.0, 1.2, length.out=7)
    

    and then in your call add

    heatmap.2(Matrix1, Colv=NA, Rowv=NA, dendrogram="none",
        ...
        breaks=mybreaks,
        ...
     )
    

    That should make them all match up.