R:ggplot:如何绘制一个正方形矩阵(非对称)作为热图? [英] R: ggplot : How do you plot a square-matrix(not symmetric) as a heatmap?

查看:76
本文介绍了R:ggplot:如何绘制一个正方形矩阵(非对称)作为热图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始方矩阵如下:

       [,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)

但是我想在此之上输入值.

But I would like to enter values on top of this.

如果我将其转换为数据框(以使用ggplot),则如下所示:

If I convert this to data frame(to use ggplot), which looks like this as expected:

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

这似乎无法产生正确的情节.请帮忙.

This doesn't seem to produce right plot. Please help.

谢谢.

推荐答案

尝试一下,

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

这篇关于R:ggplot:如何绘制一个正方形矩阵(非对称)作为热图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆