使用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/