我正试图在lower triangle
中生成heatmap
R
成对关联。
以下是数据:
set.seed(1)
mat <- matrix(rnorm(6*10),ncol=6,nrow=10)
colnames(mat) <- c("s.-.+.1","s.-.+.2","s.-.+.3","s.+.-.1","s.+.-.2","s.+.-.3")
这是我正在尝试的代码:
getUpperTri <- function(cor.mat){
cor.mat[lower.tri(cor.mat)] <- NA
return(cor.mat)
}
reorderCormat <- function(cor.mat){
dist.mat <- as.dist((1-cor.mat)/2)
hc <- hclust(dist.mat)
cor.mat <-cor.mat[hc$order,hc$order]
}
cor.df <- reshape2::melt(getUpperTri(reorderCormat(cor(mat))),na.rm=TRUE,value.name="correlation",varnames=c("sample1","sample2"))
ggplot
heatmap
代码为:
require(ggplot2)
ggplot(cor.mat.df,aes(sample2,sample1,fill=correlation))+geom_tile(color="white")+scale_fill_gradient2(low="blue",high="red",mid="white",midpoint=0,limit=c(-1,1),space="Lab",name="Pearson\nCorrelation")+theme_bw()+theme(axis.text.x=element_text(angle=45,vjust=1,size=10,hjust=1))+coord_fixed()+labs(x="",y="")
这给了我:
因此,有色元素遍布各处而不是局限于下三角。
知道问题是什么?
答案 0 :(得分:1)
只需更改
ggplot(cor.mat.df ,aes(sample2, sample1, fill=correlation))+
geom_tile(color="white")+
scale_fill_gradient2(low="blue", high="red", mid="white", midpoint=0, limit=c(-1,1), space="Lab", name="Pearson\nCorrelation")+
theme_bw()+
theme(axis.text.x=element_text(angle=45,vjust=1,size=10,hjust=1))+
coord_fixed()+
labs(x="",y="")
通过
ggplot(cor.df, aes(sample2, sample1, fill=correlation))+
geom_tile(color="white")+
scale_fill_gradient2(low="blue", high="red", mid="white", midpoint=0, limit=c(-1,1), space="Lab", name="Pearson\nCorrelation")+
theme_bw()+
theme(axis.text.x=element_text(angle=45, vjust=1, size=10, hjust=1))+
coord_fixed()+
labs(x="",y="")
我的sessionInfo:
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=Spanish_Colombia.1252 LC_CTYPE=Spanish_Colombia.1252
[3] LC_MONETARY=Spanish_Colombia.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Colombia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_2.2.1
loaded via a namespace (and not attached):
[1] Rcpp_0.12.8 digest_0.6.11 assertthat_0.1 grid_3.3.2 plyr_1.8.4
[6] gtable_0.2.0 magrittr_1.5 scales_0.4.1 stringi_1.1.2 reshape2_1.4.2
[11] lazyeval_0.2.0 labeling_0.3 tools_3.3.2 stringr_1.1.0 munsell_0.4.3
[16] colorspace_1.3-2 tibble_1.2