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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
#' Create a Heatmap
#'
#' Function creates a correlation heatmap using ggplot2 given a data.frame
#'
#' @param df A data.frame or matrix containing only numeric data.
#' @param type Identify df to be 'matrix'(default) or 'data'.
#' @param df.label A matrix for heatmap labels.
#' @param gtitle guide or legend title.
#' @param Nbreaks A number controls legend breaks.
#' @param Sig Logical, if TRUE put pvalue and sig level for heatmap labels.
#' @param data.only Logical, if TRUE returns correlation and pvalue.
heatmap1 <-
function(df,type='matrix', df.label=NULL,gtitle=NULL,
Nbreaks=NULL,Sig= FALSE,order=FALSE,
data.only = FALSE) {
require(ggplot2) # ggplot2
require(reshape2) # melt data
require(agricolae) # count corr and p.value
reorder_cormat <- function(cormat){
dd <- as.dist((1-cormat)/2)
hc <- hclust(dd)
cormat <-cormat[hc$order, hc$order]
}
if(is.null(gtitle)) gtitle<-'legend'
if(type=='data') {
#dNN=nrow(df)
df.cor.p<-correlation(df)
df1<-df.cor.p$correlation
df1.p<-df.cor.p$pvalue#-diag(dNN)
if(order==TRUE){
df1<-reorder_cormat(df1)
nm1<-rownames(df1)
df1.p<-df1.p[nm1,nm1]
}
}
if(type=='matrix') df1<-df
if(type=='corr.matrix') {
df1<-df
if(order==TRUE){
df1<-reorder_cormat(df)
nm1<-rownames(df1)
if(!is.null(df.label)) df.label<-df.label[nm1,nm1]
}
}
test <- melt(df1)
if(type=='data'){
test$p.value<-round(melt(df1.p)$value,2)
ra<-abs(test$p.value)
NN<-nrow(test)
prefix<-rep('',NN)
for(i in 1:NN){
if(ra[i]<=0.1) prefix[i] <- '.'
if(ra[i]<=0.05) prefix[i] <- '*'
if(ra[i]<=0.01) prefix[i] <- '**'
if(ra[i]<=0.001) prefix[i] <- '***'
}
ra1<-paste(test$p.value,prefix,sep='\n')
test$rp<-ra1
}
if(is.null(df.label)) {
if(Sig==FALSE) test.label=round(test$value,2)
else test.label<-test$rp
}
if(!is.null(df.label)) {test1<-melt(df.label)
if(is.numeric(test1$value)) test.label<-round(test1$value,2)
else test.label<-test1$value
}
p1<-ggplot(test,aes(x=Var1,y=Var2,fill=value,label=test.label))+
geom_tile() +
geom_text() +
labs(x="",y="",fill=gtitle)
if(is.null(Nbreaks)) p1<-p1+scale_fill_distiller(palette="Spectral",
trans = "reverse",
guide = "legend")
if(!is.null(Nbreaks)) {
bv<-unique(test$value)
bv<-bv[order(bv)]
Nbv<-length(bv)
nn<-seq(2,Nbv-1,by=Nbreaks)
bv1<-bv[c(1,nn,Nbv)]
bv2<-rev(bv1)
p1<-p1+scale_fill_distiller(palette = "Spectral",
trans = "reverse",
breaks = bv1,
guide = "legend")
}
if(data.only) {
return(test)
}
print(p1)
}
|