R:ggplot:你如何绘制一个方阵(不对称)作为热图?

时间:2012-03-15 15:11:15

标签: r ggplot2 heatmap

初始方形矩阵如下所示:

       [,1]        [,2]        [,3]        [,4]        [,5]        [,6]
[1,] 0.00000000 -0.03071266 -0.05202358 -0.06372259 -0.07458787 -0.09827112
[2,] 0.03071266  0.00000000 -0.02131092 -0.03300993 -0.04387521 -0.06755846
[3,] 0.05202358  0.02131092  0.00000000 -0.01169902 -0.02256430 -0.04624754
[4,] 0.06372259  0.03300993  0.01169902  0.00000000 -0.01086528 -0.03454853
[5,] 0.07458787  0.04387521  0.02256430  0.01086528  0.00000000 -0.02368325
[6,] 0.09827112  0.06755846  0.04624754  0.03454853  0.02368325  0.00000000
[7,] 0.13357242  0.10285976  0.08154884  0.06984982  0.05898454  0.03530130
[8,] 0.16375877  0.13304611  0.11173519  0.10003618  0.08917089  0.06548765
        [,7]        [,8]
[1,] -0.13357242 -0.16375877
[2,] -0.10285976 -0.13304611
[3,] -0.08154884 -0.11173519
[4,] -0.06984982 -0.10003618
[5,] -0.05898454 -0.08917089
[6,] -0.03530130 -0.06548765
[7,]  0.00000000 -0.03018635
[8,]  0.03018635  0.00000000

我可以像这样创建热图:

heatmap(impl_spread,symm=TRUE)

但我想在此基础上输入值。

如果我将其转换为数据框(使用ggplot),它看起来像预期的那样:

str(data)
'data.frame':   8 obs. of  8 variables:
 $ X1: num  0 0.0307 0.052 0.0637 0.0746 ...
 $ X2: num  -0.0307 0 0.0213 0.033 0.0439 ...
 $ X3: num  -0.052 -0.0213 0 0.0117 0.0226 ...
 $ X4: num  -0.0637 -0.033 -0.0117 0 0.0109 ...
 $ X5: num  -0.0746 -0.0439 -0.0226 -0.0109 0 ...
 $ X6: num  -0.0983 -0.0676 -0.0462 -0.0345 -0.0237 ...
 $ X7: num  -0.1336 -0.1029 -0.0815 -0.0698 -0.059 ...
 $ X8: num  -0.1638 -0.133 -0.1117 -0.1 -0.0892 ...

然后,

a<-c("1M","3M","6M","9M","1Y","2Y","5Y","10Y")
impl_spread[,ncol(impl_spread)+1]<-a
attach(impl_spread)
impl_spread.m<-melt(impl_spread)
impl_spread.m <- ddply(impl_spread.m, .(variable), transform, rescale = rescale(value))
ggplot(impl_spread.m,aes(V9," ")) + geom_tile(aes(fill = rescale),
colour =   "white") + scale_fill_gradient(low = "white", high = "steelblue")

这似乎没有产生正确的情节。请帮忙。

提前致谢。

1 个答案:

答案 0 :(得分:15)

试试这个,

library(reshape2)
library(ggplot2)
m = matrix(rnorm(20),5)
ggplot(melt(m), aes(Var1,Var2, fill=value)) + geom_raster()