具有对角线的热图

时间:2018-02-25 11:05:30

标签: r heatmap

我试图从对角线1的距离矩阵制作热图。实际上,距离矩阵是余弦相似度。我用“factoextra”R包中的fviz_dist绘制了这个矩阵。我想出了这个情节。

余弦相似度矩阵

如您所见,对角线表示值0.但在余弦相似度中,对角线为1,这意味着它们更相似。如何在图中将值更改为1?

1 个答案:

答案 0 :(得分:0)

TBH,我不确定你追求的是什么:这是关于如何绘制热图?或者如何手动计算余弦相异度矩阵"?无论哪种方式,这里都是一个使用一些样本数据的已完成的例子。

对于以后的帖子,请了解how to ask个好问题,并始终提供包含示例数据的minimal reproducible example/attempt

case class Relationship(name: String, opposite:Relationship)

def relationshipFactory(nameA:String, nameB:String): Relationship = {
  lazy val x:Relationship = Relationship(nameA, Relationship(nameB, x))
  x
}

val ns = relationshipFactory("North", "South")

ns // North

ns.opposite // South

ns.opposite.opposite // North

ns.opposite.opposite.opposite // South

enter image description here

注意热图中# Function to calculate cosine dissimilarity matrix # Thanks to: https://stats.stackexchange.com/a/149865/121489 cos.sim <- function(ma, mb) { mat <- tcrossprod(ma, mb); t1 <- sqrt(apply(ma, 1, crossprod)); t2 <- sqrt(apply(mb, 1, crossprod)); return(mat / outer(t1, t2)); } # Generate sample data set.seed(2017); x1 <- matrix(rnorm(45), ncol = 5); # Calculate the cosine dissimilarity matrix m <- cos.sim(x1, x1); # Show heatmap library(tidyverse); m %>% as_tibble() %>% rownames_to_column("x1") %>% gather(x2, value, 2:10) %>% mutate(x2 = gsub("V", "", x2)) %>% ggplot(aes(x1, x2)) + geom_tile(aes(fill = value)); 的1对角线。