Moving color key in R heatmap.2 (function of gplots package)
color-key, gplots, heatmap, r
Solution
The position of each element in the `heatmap.2` plot can be controlled using the `lmat`, `lhei` and `lwid` parameters. These are passed by `heatmap.2` to the `layout` command as:
layout(mat = lmat, widths = lwid, heights = lhei)
`lmat` is a matrix describing how the screen is to be broken up. By default, heatmap.2 divides the screen into a four element grid, so `lmat` is a 2x2 matrix. The number in each element of the matrix describes what order to plot the next four plots in. Heatmap.2 plots its elements in the following order:
- Heatmap,
- Row dendrogram,
- Column dendrogram,
- Key
so the default `lmat` is:
> rbind(4:3,2:1)
[,1] [,2]
[1,] 4 3
[2,] 2 1
If for example, you want to put the key underneath the heatmap you would specify:
> lmat = rbind(c(0,3),c(2,1),c(0,4))
> lmat
[,1] [,2]
[1,] 0 3
[2,] 2 1
[3,] 0 4
`lwid` and `lhei` are vectors that specify the height and width of each row and column. The default is `c(1.5,4)` for both. If you change `lmat` you'll either have to or probably want to change these as well. For the above example, if we want to keep all the other elements the same size, but want a thin color key at the bottom, we might set
>lwid = c(1.5,4)
>lhei = c(1.5,4,1)
We are then ready to plot the heatmap:
>heatmap.2(x,...,lmat = lmat, lwid = lwid, lhei = lhei)
This will plot a heatmap with the column dendrogram above the heatmap, the row dendrogram to the left, and the key underneath. Unfortunately the headings and the labels for the key are hard coded.
see `?layout` for more details on how `layout` works.
Problem
I read the heatmap.2 help manual a couple of times now, and also in various online tutorials I didn't read about a way to move the color key to a different position. Now, I am wondering if it is even possible? The color key is in the upper left corner by default if you are using the heatmap.2 function from the gplots package.