Moving color key in R heatmap.2 (function of gplot

2020-01-27 02:08发布

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.

2条回答
走好不送
2楼-- · 2020-01-27 02:24

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:

  1. Heatmap,
  2. Row dendrogram,
  3. Column dendrogram,
  4. 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.

查看更多
地球回转人心会变
3楼-- · 2020-01-27 02:39

There are specified regions defined by par calls in the rather long code for heatmap.2 and I have not seen its original author or any of the "revisors" around these parts, although they sometimes visit on R-help. The main plot dimensions are set by the 2-element vector margins. Here are some places where you might need to make changes:

#1) 
if (!missing(RowSideColors)) {
    par(mar = c(margins[1], 0, 0, 0.5))
    image(rbind(1:nr), col = RowSideColors[rowInd], axes = FALSE)

#2)
if (!missing(ColSideColors)) {
    par(mar = c(0.5, 0, 0, margins[2]))
    image(cbind(1:nc), col = ColSideColors[colInd], axes = FALSE)

#3)
par(mar = c(margins[1], 0, 0, margins[2]))

#4)
par(mar = c(margins[1], 0, 0, 0))

#5)
par(mar = c(0, 0, if (!is.null(main)) 5 else 0, margins[2]))

#6
if (key) {
    par(mar = c(5, 4, 2, 1), cex = 0.75)
查看更多
登录 后发表回答