1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| < 大专栏 记录R的一些黑魔法td class="code">
ggheat=function(m, rescaling='none', clustering='none', labCol=T, labRow=T, border=FALSE,
heatscale= c(low='blue',high='red'))
{
require(reshape2)
require(ggplot2)
if(is.function(rescaling))
{
m=rescaling(m)
}
else
{
if(rescaling=='column')
m=scale(m, center=T)
if(rescaling=='row')
m=t(scale(t(m),center=T))
}
if(is.function(clustering))
{
m=clustering(m)
}else
{
if(clustering=='row')
m=m[hclust(dist(m))$order, ]
if(clustering=='column')
m=m[,hclust(dist(t(m)))$order]
if(clustering=='both')
m=m[hclust(dist(m))$order ,hclust(dist(t(m)))$order]
}
rows=dim(m)[1]
cols=dim(m)[2]
melt.m=cbind(rowInd=rep(1:rows, times=cols), colInd=rep(1:cols, each=rows) ,melt(m))
g=ggplot(data=melt.m)
if(border==TRUE)
g2=g+geom_rect(aes(xmin=colInd-1,xmax=colInd,ymin=rowInd-1,ymax=rowInd, fill=value),colour='white')
if(border==FALSE)
g2=g+geom_rect(aes(xmin=colInd-1,xmax=colInd,ymin=rowInd-1,ymax=rowInd, fill=value))
if(labCol==T)
g2=g2+scale_x_continuous(breaks=(1:cols)-0.5, labels=colnames(m))
if(labCol==F)
g2=g2+scale_x_continuous(breaks=(1:cols)-0.5, labels=rep('',cols))
if(labRow==T)
g2=g2+scale_y_continuous(breaks=(1:rows)-0.5, labels=rownames(m))
if(labRow==F)
g2=g2+scale_y_continuous(breaks=(1:rows)-0.5, labels=rep('',rows))
return(g2+scale_fill_continuous("", heatscale[1], heatscale[2]))
}