从 R 中的 PCA 坐标创建热图

甜蜜的音乐

我想针对自身的一个变量创建一个热图。但是,我没有矩阵格式。我有每个项目的 PCA1 和 PCA2 坐标,我想知道如何从中创建热图。这就是我的数据的样子(其中 cluster 是 k-means 聚类分类)

ID                     PCA1             PCA2          cluster
echocardiography       -0.88            0.87          9
infarction             -0.18            0.57          7
carotid                1.13             -0.80         2
aorta                  -0.03            -0.06         5
myocardial             -0.72            -0.02         3
hemorrhage             0.23             -0.67         5

所以基本上我想要一个 ID 之间的热图,显示(通过可能使用 PCA 坐标距离)每个 ID 的相关性。

注意:热图应该看起来像这样(相对于密度热图): 在此处输入图片说明

马可·桑德里

这是一个可能的解决方案。希望它可以帮助你。

df <- structure(list(ID = structure(c(3L, 5L, 2L, 1L, 6L, 4L), .Label = c("aorta", 
"carotid", "echocardiography", "hemorrhage", "infarction", "myocardial"
), class = "factor"), PCA1 = c(-0.88, -0.18, 1.13, -0.03, -0.72, 
0.23), PCA2 = c(0.87, 0.57, -0.8, -0.06, -0.02, -0.67), cluster = c(9L, 
7L, 2L, 5L, 3L, 5L)), .Names = c("ID", "PCA1", "PCA2", "cluster"
), class = "data.frame", row.names = c(NA, -6L))

# Define a distance function based on euclidean norm
# calculated between PCA values of the i-th and j-th items
dst <- Vectorize(function(i,j,dtset) sqrt(sum((dtset[i,2:3]-dtset[j,2:3])^2)), vectorize.args=c("i","j"))

# Here is the distance between echocardiography and infarction
dst(1,2,df)
# [1] 0.7615773
# This value is given by
sqrt(sum((df[1,2:3] - df[2,2:3])^2))

# Calculate the distance matrix
nr <- nrow(df)
mtx <- outer(1:nr, 1:nr, "dst", dtset=df)
colnames(mtx) <- rownames(mtx) <- df[,1]

# Plot the heatmap using ggplot2
library(reshape2)
library(ggplot2)
mtx.long <- melt(mtx)
ggplot(mtx.long, aes(x = Var1, y = Var2, fill = value)) + geom_tile()+xlab("")+ylab("")

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章