使用R包pheatmap绘制热图。有没有一种方法可以给输入矩阵中的NAs分配颜色?似乎在默认情况下,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)谢谢
发布于 2014-09-19 18:26:37
这是可能的,但需要一些技巧。
首先,让我们看看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来决定使用哪种颜色。
让我们试着看看如果周围有NAs,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的代码,并让它按照您的意愿处理NAs……
发布于 2017-04-16 22:03:15
您可以使用来自github的开发人员版本的pheatmap来启用颜色分配。您可以使用devtools执行此操作:
#this part loads the dev pheatmap package from github
if (!require("devtools")) {
install.packages("devtools", dependencies = TRUE)
library(devtools)
}
install_github("raivokolde/pheatmap")现在您可以在pheatmap函数中使用参数"na_col“:
pheatmap(..., na_col = "grey", ...)(编辑)之后别忘了加载它。安装完成后,您可以将其视为任何其他已安装的软件包。
发布于 2020-08-01 07:32:32
实际上,现在问题很简单。当前的pheatmap函数结合了一个参数,用于将颜色分配给"NA",即na_col。示例:
na_col = "grey90"https://stackoverflow.com/questions/25929991
复制相似问题