正如在 cmets 中提到的,问题是您的数据集可能有 > 2 个维度(超过 2 个变量),而您的图被限制为 2 个(或者可能是 3 个)维度。所以需要某种降维。典型的方法是对原始数据进行主成分分析,然后绘制前两台 PC,按集群组织。因此,这里有三种在 R 中执行此操作的方法,以 mtcars 数据集为例。
df <- mtcars[,c(1,3,4,5,6,7)] # subset of mtcars dataset
set.seed(1) # for reproducible example
km <- kmeans(df,centers=3) # k-means, 3 clusters
# using package cluster
library(cluster)
clusplot(df,km$cluster)
# using package ade4
library(ade4)
pca <-prcomp(df, scale.=T, retx=T) # principal components analysis
plot.df <- cbind(pca$x[,1], pca$x[,2]) # first and second PC
s.class(plot.df, factor(km$cluster))
# ggplot solution
pca <-prcomp(df, scale.=T, retx=T) # principal components analysis
# gg: data frame of PC1 and PC2 scores with corresponding cluster
gg <- data.frame(cluster=factor(km$cluster), x=scores$PC1, y=scores$PC2)
# calculate cluster centroid locations
centroids <- aggregate(cbind(x,y)~cluster,data=gg,mean)
# merge centroid locations into ggplot dataframe
gg <- merge(gg,centroids,by="cluster",suffixes=c("",".centroid"))
# calculate 95% confidence ellipses
library(ellipse)
conf.rgn <- do.call(rbind,lapply(1:3,function(i)
cbind(cluster=i,ellipse(cov(gg[gg$cluster==i,2:3]),centre=as.matrix(centroids[i,2:3])))))
conf.rgn <- data.frame(conf.rgn)
conf.rgn$cluster <- factor(conf.rgn$cluster)
# plot cluster map
library(ggplot2)
ggplot(gg, aes(x,y, color=cluster))+
geom_point(size=3) +
geom_point(data=centroids, size=4) +
geom_segment(aes(x=x.centroid, y=y.centroid, xend=x, yend=y))+
geom_path(data=conf.rgn)
请注意,这三个选项都给出了不同的省略号!这是因为它们的定义不同。 clusplot(...) 默认情况下会生成“最小体积椭圆”,它具有正确的中心和方向,但大小刚好足以包含集群中的所有点。 s.plot(...) 根据可在调用参数中设置的比例因子生成椭圆。 ggplot(...) 解决方案生成的椭圆是每个集群的 95% 置信区域(假设每个集群中的点服从二元正态分布)。从中可以看出,集群明显重叠;也就是说,有几个点可能属于多个集群。这给出了更真实的数据表示,IMO,这是我喜欢它的原因之一,尽管它显然需要更多的工作。