Mizzle
Mizzle

Reputation: 757

Add a gap with black color or border line in heatmap with pheatmap package

Here is my R code below. Now there are two white gaps by the command gaps_col = c(2,4). I Would like to change the white gap to black or add black border line at the position of the gap. How can I do that?

What's more, I would also like to change the colnames. I would like to replace P1 and P2 by P in the middle of P1 and P2. I would like to replace Q1 and Q2 by Q in the middle of Q1 and Q2. I would like to replace T1 and T2 by T in the middle of T1 and T2.

library(pheatmap)   
set.seed(123)
df<-data.frame( matrix(sample(30), ncol = 5))
colnames(df)<-LETTERS[1:5]
subj<-c("P1", "P2","Q1", "Q2", "T1","T2")
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 =  c(2,4),
         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

Upvotes: 0

Views: 1730

Answers (1)

cazman
cazman

Reputation: 1492

This seems like it is a HUGE hack and maybe there is a better way to do it, but it doesn't seem like pheatmap supports this functionality out of the box. I was able to generate what I think you want, but the exact dimensions and positioning of each of the layers will depend on the output size of the plot. Basically, I drew a black rectangle to have behind the plot, drew the letter annotations that you want at the bottom of the plot, created the heat map without column names, resized it, and essentially added the layers to the plot.

bg_color <- "black"
bg <- rasterGrob(bg_color,
                 x = 0.5,
                 y = 0.395,
                 width = unit(0.5, "npc"),
                 height = unit(0.82, "npc"),
                 interpolate = TRUE,
                 vjust = 0.4)

text_p <- richtext_grob("P",
                 x = 0.15,
                 y = 0.025)

text_q <- richtext_grob("Q",
                        x = 0.44,
                        y = 0.025)

text_t <- richtext_grob("T",
                        x = 0.73,
                        y = 0.025)

hm <- pheatmap(t(scale(df)),
         annotation_col = aka2, 
         annotation_colors = aka3[1],
         annotation_legend = FALSE,
         gaps_col =  c(2,4),
         show_colnames = F, show_rownames = T, cluster_rows = F, 
         cluster_cols = F, legend = TRUE, 
         clustering_distance_rows = "euclidean", border_color = FALSE)

hm$gtable$vp$height <- unit(0.9, "npc")

grid.newpage()
grid.draw(bg)
grid.draw(text_p)
grid.draw(text_q)
grid.draw(text_t)
print(hm, newpage = FALSE)

The result is:

enter image description here

Upvotes: 1

Related Questions