如何在R中在主热图旁边添加一个额外的单列热图

7
我有以下脚本:
library("gplots")
mydata <- mtcars
mydata.nr <- nrow(mydata)
mydata.newval <-  data.frame(row.names=rownames(mydata),new.val=-log(runif(mydata.nr)))

# Functions
hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) dist(x,method="euclidean")

# Set colors
hmcols <- rev(redgreen(256));

# Plot the scaled data
heatmap.2(as.matrix(mydata),dendrogram="row",scale="row",col=hmcols,trace="none", margin=c(8,9), hclust=hclustfunc,distfun=distfunc);

生成以下热力图:

enter image description here

现在给出一个包含每辆车新值的新数据框:

mydata.nr <- nrow(mydata)
mydata.newval <-  data.frame(row.names=rownames(mydata),new.val=-log(runif(mydata.nr)))

我想在R的heatmap.2中创建一个单列的热图,热图旁边有渐变灰色,并带有行名称。如何实现?


3
我建议使用清除式方法:查看persp3D或其他默认在其图形中放置颜色刻度的软件包的源代码,并复制代码以供您自己使用。 - Carl Witthoft
如果你想要更多的灵活性,可以尝试使用ggplot。https://dev59.com/cmw15IYBdhLWcg3wWqV0 - kdauria
1个回答

3

这个功能是否符合您的需求?您可以使用 RowSideColors 选项在热力图侧边添加一列。

new.vals = mydata.newval[,1]
mydata.newval$scaled = ( new.vals - min(new.vals) ) / 
                       ( max(new.vals) - min(new.vals) )
mydata.newval$gray = gray( mydata.newval$scaled )

heatmap.2( as.matrix(mydata), 
           dendrogram = "row", scale = "row",
           col = hmcols, trace = "none", 
           margin = c(8,9), 
           hclust = hclustfunc, distfun = distfunc,
           RowSideColors=mydata.newval$gray )

图片描述

如果您想要在热力图和标签之间加入灰色列,则使用heatmap.2并没有简单的方式来实现这一点;我认为它不是为此目的而设计的。一种拼凑的方法是将灰色值从10到11(或其他超出其余数据范围的值)。然后,您需要更改分段映射到颜色(请参见这里)。但是,这会使您的关键字看起来相当奇怪。

# heatmap.2 does the clustering BEFORE the scaling. 
# Clustering after scaling might give different results
# heatmap.2 also reorders the dendrogram according to rowMeans.
# (Code copied directly from the heatmap.2 function)
x = as.matrix(mydata)
Rowv = rowMeans(x, na.rm = TRUE)
hcr = hclustfunc(distfunc(x))
ddr = as.dendrogram(hcr)
ddr = reorder(ddr, Rowv) # the row dendrogram

# Scale the data as heatmap.2 does
rm = rowMeans(x, na.rm = TRUE)
x = sweep(x, 1, rm)
sx =  apply(x, 1, sd, na.rm = TRUE)
x = sweep(x, 1, sx, "/")

# add the new data as a column
new.vals = mydata.newval[,1]
new.vals.scaled = ( new.vals - min(new.vals) ) / 
                  ( max(new.vals) - min(new.vals) ) # scaled from 0 to 1
x = cbind( x, gray = max(x) + new.vals.scaled + 0.1 )

# make the custom breaks and colors
edge = max(abs(x-1.1))
breaks = seq(-edge,edge+1.1,length.out=1000)
gradient1 = greenred( sum( breaks[-length(breaks)] <= edge ) )
gradient2 = colorpanel( sum( breaks[-length(breaks)] > edge ), "white", "black" )
hm.colors = c(gradient1,gradient2)

hm = heatmap.2( x, col=hm.colors, breaks=breaks,
           scale="none", 
           dendrogram="row", Rowv=ddr,
           trace="none", margins=c(8,9) )

尽管这种方法可行,但我建议使用更灵活的软件包,通过使用 grid 包来处理不同的视口,寻找更强大的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接