rpheatmap

How to label some rowname of heatmap in bold and other in italic


I found an interesting function to label in bold some rownames of heatmap. I have adapted it to do the same in italic and I would like to know, how I can adapt more this code, in order to put some rowname in bold and others in italic. Please find the two functions and the heatmap (I am using the same example found to explain the function).

library(pheatmap)
library(tidyverse)

# Create test matrix
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_bold_names <- function(mat, rc_fun, rc_names) {
  bold_names <- rc_fun(mat)
  ids <- rc_names %>% match(rc_fun(mat))
  ids %>%
    walk(
      function(i)
        bold_names[i] <<-
        bquote(bold(.(rc_fun(mat)[i]))) %>%
        as.expression()
    )
  bold_names
}


make_italic_names <- function(mat, rc_fun, rc_names) {
  italic_names <- rc_fun(mat)
  ids <- rc_names %>% match(rc_fun(mat))
  ids %>%
    walk(
      function(i)
        italic_names[i] <<-
        bquote(italic(.(rc_fun(mat)[i]))) %>%
        as.expression()
    )
  italic_names
}

pheatmap(
  test,
  labels_row = make_bold_names(test, rownames, c("Gene2", "Gene5", "Gene14")))



enter image description here

using two labels_row is obviously not working

pheatmap(
  test,
  labels_row = make_bold_names(test, rownames, c("Gene2", "Gene5", "Gene14")),
  labels_row = make_italic_names(test, rownames, c("Gene3", "Gene6", "Gene10")))

Solution

  • Obviously, you cannot pass the same argument twice in the function.

    Instead, you can edit the custom function in a way that it accommodates both bold face and italic together. Here is the code:

    make_face_names <- function(mat, rc_fun, rc_names_b = NA, 
                                rc_names_i = NA) {
      f_names <- rc_fun(mat)
      ids_b <- rc_names_b %>% match(rc_fun(mat))
      ids_i <- rc_names_i %>% match(rc_fun(mat))
      
      ids_b %>%
        walk(
          function(i)
            f_names[i] <<-
            bquote(bold(.(rc_fun(mat)[i]))) %>%
            as.expression()
        )
      ids_i %>%
        walk(
          function(i)
            f_names[i] <<-
            bquote(italic(.(rc_fun(mat)[i]))) %>%
            as.expression()
        )
      
      f_names
    }
    
    
    pheatmap(test,
             labels_row = make_face_names(test,
                                          rownames, rc_names_b = c("Gene2", "Gene5", "Gene14"),
                                          rc_names_i = c("Gene3", "Gene6", "Gene10")))
    

    enter image description here