如何在R中的PAM中获取主组件数据

时间:2019-12-06 05:56:43

标签: r ggplot2 cluster-analysis pca ggfortify

我使用mtcars数据使用 autoplot 函数创建了一个图形,并得到了这样的图形

enter image description here

这是我的代码:

library(cluster)
library(NbClust)
library(ggplot2)
library(ggfortify)
x <- mtcars
number.cluster <- NbClust(x, distance = "euclidean", min.nc = 1, max.nc = 5, method = "complete", index = "ch")
best.cluster <- as.numeric(number.cluster$Best.nc[1])
x.pam <- pam(x, best.cluster)
autoplot(x.pam, data = x, frame = T) + ggtitle("PAM MTCARS")

我的问题是如何根据此图获取PC1和PC2数据坐标? 谢谢

2 个答案:

答案 0 :(得分:4)

您可以使用layer_data()获取用于ggplot对象的数据:

p <- autoplot(x.pam, data = x, frame = T) + ggtitle("PAM MTCARS")
layer_data(p, 1L) # coordinates of all points
layer_data(p, 2L) # coordinates of points that contribute to polygons

答案 1 :(得分:2)

您的整个过程都有缺陷。首先,您使用完整的链接来估计群集的数量;但是您没有使用找到的“最佳”集群,而是再次使用PAM集群。 您使用欧几里得距离,但是在欧几里得空间中,k均值通常比PAM效果更好-当您没有欧几里得几何形状且不能使用k-means时,PAM会发光。

然后您要使用此PCA图,该图严重失真(几乎所有方差都在第一个分量中,y轴显示了很多随机偏差)。如果您需要这些坐标,只需使用PCA,而不是从绘图中重新构建。