从R中的PCA坐标创建热图

时间:2017-06-24 00:01:12

标签: r matrix heatmap text-mining pca

我想在一个变量上创建一个热图来反对自己。但是,我没有矩阵格式。我有每个项目的PCA1和PCA2坐标,我想知道如何创建一个热图。这就是我的数据(群集是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的相关性。

注意:热图应该看起来像这样(对比密度热图): enter image description here

1 个答案:

答案 0 :(得分:1)

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

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("")

enter image description here