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

我有以下脚本:

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);

其中生成以下热图: 在这里输入图像描述

现在给出一个新的data.frame,它包含每个汽车的新值:

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

我想创建一个带有渐变灰色的单列热图,位于行名旁边。 我怎样才能在R heatmap.2中实现这一点?


这是否做你想要的? 您可以使用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包与不同的视口一起玩。

链接地址: http://www.djcxy.com/p/18091.html

上一篇: How to add an additional single column heatmap at the side of main heatmap in R

下一篇: IPython Notebook: Open/select file with GUI (Qt Dialog)