刻度标签的 pheatmap 离散颜色图放置

pheatmap discrete colormap placement of tick labels

我有一个包含数千个单元格的矩阵,值范围为 0-5。我想使用离散的调色板来指示各个单元格的值。 此代码已经运行良好,但颜色图标签的位置已关闭。 我只是想,每个刻度都在相应颜色的中心..

library("pheatmap")
library("RColorBrewer")

matrix <- round(matrix(rexp(200, rate=.1), ncol=20)/10)
color <- brewer.pal(max(matrix)+1,"Blues")
pheatmap(matrix,color=color,cluster_rows = F,cluster_cols = F)

该示例生成如下热图:

我想移动颜色条标签,所以它看起来更像这样:

如果有人知道如何做到这一点,我将不胜感激!

您可以处理图例标签 (p$gtable$grobs[[2]]$children[[2]]) 的文本乱码。
标签的y轴位置定义如下:

library("pheatmap")
library("RColorBrewer")

set.seed(123)
matrix <- round(matrix(rexp(200, rate=.1), ncol=20)/10)
color <- brewer.pal(max(matrix)+1,"Blues")
p <- pheatmap(matrix, color=color,cluster_rows = F,
              cluster_cols = F, silent=T)

p$gtable$grobs[[2]]$children[[2]]$y

[1] sum(0*min(1npc, 150bigpts), 1npc, -1*min(1npc, 150bigpts))
[2] sum(0.142857142857143*min(1npc, 150bigpts), 1npc, -1*min(1npc, 150bigpts))
    ....
[8] sum(min(1npc, 150bigpts), 1npc, -1*min(1npc, 150bigpts))

可以通过更改第一个 min 之前的乘法常数来修改标签位置(00.1428、...、1)。

# Sometimes the number of colored areas in the legend is not 
# equal to the number of labels    
N_col_areas <- length(p$gtable$grobs[[2]]$children[[1]]$y)
N_labels <- length(p$gtable$grobs[[2]]$children[[2]]$label)
yseq1 <- seq(0, 1, length.out=N_col_areas)
center <- yseq1[2]/2
yseq2 <- seq(center, 1-center, length.out=N_labels)

for (k in 1:(N_labels)) {
  p$gtable$grobs[[2]]$children[[2]]$y[[k]] <- 
          sum(yseq2[k]*min(unit(1,"npc"), unit(150,"bigpts")), 
              unit(1,"npc"), 
              -1*min(unit(1,"npc"), unit(150,"bigpts")))
}
plot.new()
print(p)