r - pheatmap:NA 的颜色

标签 r na pheatmap

使用R包pheatmap绘制热图。有没有办法为输入矩阵中的 NA 分配颜色?看来 NA 默认情况下是白色的。 例如:

library(pheatmap)
m<- matrix(c(1:100), nrow= 10)
m[1,1]<- NA
m[10,10]<- NA
pheatmap(m, cluster_rows=FALSE, cluster_cols=FALSE)

谢谢

最佳答案

这是可能的,但需要一些黑客技术。

首先让我们看看pheatmap如何绘制热图。您只需在控制台中输入 pheatmap 并滚动浏览输出,或者使用 edit(pheatmap) 即可进行检查。

您会发现颜色是使用映射的

mat = scale_colours(mat, col = color, breaks = breaks)

scale_colours函数似乎是pheatmap包的内部函数,但我们可以使用以下命令查看源代码

getAnywhere(scale_colours)

这给出

function (mat, col = rainbow(10), breaks = NA) 
{
    mat = as.matrix(mat)
    return(matrix(scale_vec_colours(as.vector(mat), col = col, 
        breaks = breaks), nrow(mat), ncol(mat), dimnames = list(rownames(mat), 
        colnames(mat))))
}

现在我们需要检查scale_vec_colours,结果是:

function (x, col = rainbow(10), breaks = NA) 
{
    return(col[as.numeric(cut(x, breaks = breaks, include.lowest = T))])
}

因此,本质上,pheatmap 使用 cut 来决定使用哪些颜色。

让我们尝试看看如果周围有 NA,cut 会做什么:

as.numeric(cut(c(1:100, NA, NA), seq(0, 100, 10)))
  [1]  1  1  1  1  1  1  1  1  1  1  2  2  2  2  2  2  2  2  2  2  3  3  3  3  3  3  3  3
 [29]  3  3  4  4  4  4  4  4  4  4  4  4  5  5  5  5  5  5  5  5  5  5  6  6  6  6  6  6
 [57]  6  6  6  6  7  7  7  7  7  7  7  7  7  7  8  8  8  8  8  8  8  8  8  8  9  9  9  9
 [85]  9  9  9  9  9  9 10 10 10 10 10 10 10 10 10 10 NA NA

它返回 NA!所以,这就是你的问题!

现在,我们如何解决这个问题? 最简单的事情是让 pheatmap 绘制热图,然后根据需要绘制 NA 值。

再次查看 pheatmap 函数,您会发现它使用 grid 包进行绘图(另请参阅此问题:R - How do I add lines and text to pheatmap?)

因此您可以使用grid.rect将矩形添加到NA位置。 我要做的就是通过反复试验找到热图边框的坐标,然后从那里绘制矩形。

例如:

library(pheatmap)
m<- matrix(c(1:100), nrow= 10)
m[1,1]<- NA
m[10,10]<- NA

hmap <- pheatmap(m, cluster_rows=FALSE, cluster_cols=FALSE)
# These values were found by trial and error
# They WILL be different on your system and will vary when you change
# the size of the output, you may want to take that into account.
min.x <- 0.005
min.y <- 0.01
max.x <- 0.968
max.y <- 0.990
width <- 0.095
height <- 0.095

coord.x <- seq(min.x, max.x-width, length.out=ncol(m))
coord.y <- seq(max.y-height, min.y, length.out=nrow(m))

for (x in seq_along(coord.x))
  {
  for (y in seq_along(coord.y))
    {
    if (is.na(m[x,y]))
        grid.rect(coord.x[x], coord.y[y], just=c("left", "bottom"),
                  width, height, gp = gpar(fill = "green"))    
    }
  }

更好的解决方案是使用 edit 函数破解 pheatmap 的代码,并让它按照您的意愿处理 NA...

关于r - pheatmap:NA 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25929991/

相关文章:

r - 如何在图表左侧显示 pheatmap 中的行名?

r - 计算级别内的值

r - 如何在 R 中绘制 CDF

r - 通过其他日期列中的信息填充缺失的变量 (R)

r - 使用 NA 计算列中位数

r - 仅对最后一个值插入 NA

r - 如何从 R pheatmap 获取色标值(行 z 分值)

r - 合并在 R 中产生意想不到的结果

r - 在条形图中的主网格线之间添加网格线

r - 在 R 中使用 pheatmap 绘制相关性时,可以绘制下三角矩阵图或上三角矩阵图吗?