Search code examples
rpheatmap

Pheatmap annotation colors and border


Pheatmap library(pheatmap) takes annotation_colorsto add the header ID colors on the top of each heatmap column.

I want to add white as column header color with borders. Border can be added by border_color but this function draws borders also to the whole heatmap.

Below is what I have done so far.

library(pheatmap)   
set.seed(123)
df<-data.frame( matrix(sample(30), ncol = 5))
colnames(df)<-LETTERS[1:5]
subj<-c("P1", "P2","P3", "T1", "T2","T3")
rownames(df)<-subj
aka2 = data.frame(ID = factor(rep(c("Pat","Trea"), each=3)))
rownames(aka2)<-subj
aka3 = list(ID = c(Pat = "white", Trea="blue"))
pheatmap(t(scale(df)),
         annotation_col = aka2, 
         annotation_colors = aka3[1],
         annotation_legend = FALSE,
         gaps_col =  3,
         show_colnames = T, show_rownames = T, cluster_rows = F, 
         cluster_cols = F, legend = TRUE, 
         clustering_distance_rows = "euclidean", border_color = FALSE)

enter image description here


Solution

  • I use grid functions to edit the relevant grob:

    library(pheatmap)   
    set.seed(123)
    df<-data.frame( matrix(sample(30), ncol = 5))
    colnames(df)<-LETTERS[1:5]
    subj<-c("P1", "P2","P3", "T1", "T2","T3")
    rownames(df)<-subj
    aka2 = data.frame(ID = factor(rep(c("Pat","Trea"), each=3)))
    rownames(aka2)<-subj
    aka3 = list(ID = c(Pat = "white", Trea="blue"))
    
    pheatmap(t(scale(df)),
             annotation_col = aka2, 
             annotation_colors = aka3[1],
             annotation_legend = FALSE,
             gaps_col =  3,
             show_colnames = T, show_rownames = T, cluster_rows = F, 
             cluster_cols = F, legend = TRUE, 
             clustering_distance_rows = "euclidean", border_color = FALSE)
    
    # Edit the relevant grob
    library(grid)
    grid.ls(grid.force()) # "col_annotation" looks like it's the one to edit
    grid.gedit("col_annotation", gp = gpar(col="grey70"))
    

    Applying grid.gget("col_annotation")$gp to the original heatmap shows that col_annotation does have a gp slot with fill set but no col. After the edit, both fill and col are set.

    enter image description here