Search code examples
rstringgridpheatmap

How to force the row labels in a fixed width and be aligned in pheatmap in R?


Usually there is no problem to show the row labels in pheatmap in R. However, see I have a little bit complicated row labels which are strings that combined a head of one string and an end of another string. For example, "ABC**** 123".

Here is an example and my code:

library(pheatmap)
library(stringr)

# create an example
test = matrix(rnorm(200), 20, 10)
test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3
test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2
test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4
colnames(test) = paste("Test", 1:10, sep = "")
rownames(test) = paste("Gene", 1:20, sep = "")

# make random pvalue to show at the end of rownames
random.pvalue <- formatC(runif(n = 20,min = 0.0000000000001,max = 0.00000000001),format = "e",
                         digits = 2)

# creat new rownames with fixed width
add.label <- paste0(str_pad(rownames(test),
                    width=12, 
                    side="right"),
                    random.pvalue)

rownames(test) <- add.label # update rownames
# Draw heatmaps
pheatmap(test) # you could see the pvalues are not aligned

Trust me I have forced these row labels in a fixed width by using formatC() and str_pad() in R. However, when I used pheatmap with those row labels, the labels did not show as I thought, they went like the following, and you can clearly see that the row labels are not aligned even they have the same string width.

 [1] "Gene1       7.77e-12" "Gene2       2.67e-12" "Gene3       8.67e-12" "Gene4       6.61e-12"
 [5] "Gene5       2.36e-12" "Gene6       3.09e-12" "Gene7       5.44e-12" "Gene8       3.18e-13"
 [9] "Gene9       1.34e-12" "Gene10      4.52e-12" "Gene11      2.03e-12" "Gene12      5.31e-12"
[13] "Gene13      9.66e-12" "Gene14      9.02e-12" "Gene15      2.91e-13" "Gene16      7.37e-13"
[17] "Gene17      7.95e-12" "Gene18      8.04e-12" "Gene19      8.31e-12" "Gene20      9.94e-12"

Maybe someone could use a simple example to teach me how to fix this.

Many thanks advanced!

enter image description here


Solution

  • You could use a fixed font (not a proportional one):

    library(pheatmap)
    library(grid)
    library(stringr)
    mat <- mtcars[1:10,1:6]
    rn <- stringr::str_pad(rownames(mat), max(nchar(rownames(mat))), side = "right")
    p <- signif(1e-9*mat[,4], digits = 4)
    pheatmap::pheatmap(as.matrix(mtcars[1:10,1:6]), scale="column", 
        labels_row=paste(rn, p, sep="    "), fontfamily = "mono")