Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: ggplot : How do you plot a square-matrix(not symmetric) as a heatmap?

Tags:

r

ggplot2

heatmap

The initial square matrix looks like this:

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

I can create heatmap like this:

heatmap(impl_spread,symm=TRUE)

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

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 ...

And, then,

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.

Thanks in advance.

like image 737
Neerav Avatar asked Mar 15 '12 15:03

Neerav


1 Answers

Try this,

library(reshape2)
library(ggplot2)
m = matrix(rnorm(20),5)
ggplot(melt(m), aes(Var1,Var2, fill=value)) + geom_raster()
like image 188
baptiste Avatar answered Nov 11 '22 08:11

baptiste