user1795995
user1795995

Reputation: 51

Color Labels (text) in R heatmap

I am trying to make a heatmap in R in which the label text is colored (to indicate which group the data point comes from).

I am currently using heatmap.2, but would be happy to use another package.

heatmap.2(data.matrix(data),trace = 'none', dendrogram='none',ColSideColors=col)

This call gives me the colored bar (ColSideColors) along the labels, but I'd like to make the labels themselves colored.

Many thanks!

Upvotes: 5

Views: 6472

Answers (3)

procrastinator
procrastinator

Reputation: 1

I can't reply to lwz0203 due to lack of commenting permissions, but their code is not quite complete. You need to add the lines:

if(is.vector(RlabColor)) {
    RlabColor=RlabColor[rowInd]
}

(and analagously for ClabColor)

if(is.vector(ClabColor)) {
    ClabColor=ClabColor[colInd]
}

at some point in the code or you will get the coloring mis-matching with the labels when you use a vector of colors. The text in the vector labRow or labCol gets reordered already with the code:

if (is.null(labRow))
    labRow <- if (is.null(rownames(x)))
        (1:nr)[rowInd]
        else rownames(x)
else labRow <- labRow[rowInd] 

So I add reordering of RlabColor and ClabColor in the same place.

Upvotes: 0

lwz0203
lwz0203

Reputation: 21

I had the same problem recently, and I ended up using mtext to replace the original axis. Previous answers have shown the axis statement to plot the labels. However, col.axis could only specify one color. To enable vector color,

#    axis(1, 1:nc, labels = labCol, las = 2, line = -0.5, tick = 0, 
#        cex.axis = cexCol )
mtext(side = 1, text = labCol, at = 1:nc, las = 2, line = 0.5,col = ClabColor, cex = cexCol)


#    axis(4, iy, labels = labRow, las = 2, line = -0.5, tick = 0, 
#        cex.axis = cexRow )
mtext(side = 4, text = labRow, at = iy, las = 2, line = 0.5,col = RlabColor, cex = cexCol)

Also, remember to add two more arguments to the function, ClabColor = "black", RlabColor = "black". The default colors are black.

Another thing you need to pay attention to is that, the vector color should follow the order of the labels, which are permuted when you compute dendrograms

Upvotes: 0

IRTFM
IRTFM

Reputation: 263489

You will need to create a new function that includes the col.axis argument. These are the line of the function to work with:

# there were four long pages of code before this section:

axis(1, 1:nc, labels = labCol, las = 2, line = -0.5, tick = 0, # original line
        col.axis="green",   # added argument
        cex.axis = cexCol)
if (!is.null(xlab)) 
        mtext(xlab, side = 1, line = margins[1] - 1.25)
axis(4, iy, labels = labRow, las = 2, line = -0.5, tick = 0, # original line
        col.axis="green",   # added argument
        cex.axis = cexRow)

Upvotes: 3

Related Questions