向R中的K-均值聚类图添加标签
我用我在网上找到的一些R代码制作了一个K-均值聚类图,如下所示:向R中的K-均值聚类图添加标签,r,plot,R,Plot,我用我在网上找到的一些R代码制作了一个K-均值聚类图,如下所示: dtmr <-DocumentTermMatrix(docs,control=list(wordLengths=c(4,15), bounds = list(global = c(50,500)))) ## do tfxidf dtm_tfxidf <- weightTfIdf(dtmr) ### k-means (this uses euclidean distance) m <- as.matrix(dtm
dtmr <-DocumentTermMatrix(docs,control=list(wordLengths=c(4,15), bounds = list(global = c(50,500))))
## do tfxidf
dtm_tfxidf <- weightTfIdf(dtmr)
### k-means (this uses euclidean distance)
m <- as.matrix(dtm_tfxidf)
rownames(m) <- 1:nrow(m)
### don't forget to normalize the vectors so Euclidean makes sense
norm_eucl <- function(m) m/apply(m, MARGIN=1, FUN=function(x) sum(x^2)^.5)
m_norm <- norm_eucl(m)
### cluster into 5 clusters
cl <- kmeans(m_norm, 5)
table(cl$cluster)
### show clusters using the first 2 principal components
plot(prcomp(m_norm)$x, col=cl$cl, text(m_norm, mpg, row.names(m)))
dtmr我能看到的问题是text()
在plot
调用中,当它应该在调用之后出现时,传递给text
的x
和y
与用于生成plot的prcomp
的结果不同
我正在使用mtcars
作为数据集:
df<- mtcars
### k-means (this uses euclidean distance)
m <- as.matrix(df)
rownames(m) <- 1:nrow(m)
### don't forget to normalize the vectors so Euclidean makes sense
norm_eucl <- function(m) m/apply(m, MARGIN=1, FUN=function(x) sum(x^2)^.5)
m_norm <- norm_eucl(m)
### cluster into 5 clusters
cl <- kmeans(m_norm, 5)
table(cl$cluster)
### show clusters using the first 2 principal components
# do the PCA outside the plot function for now
PCA <-prcomp(m_norm)$x
#plot then add labels
plot(PCA, col=cl$cl)
text(x=PCA[,1], y=PCA[,2], cex=0.6, pos=4, labels=(row.names(m)))
df您应该在问题中包含一小部分具有代表性的数据样本,以便人们更容易复制您想要的行为。如果今晚没有人回应,我家里有一些代码,基本上就是使用ggplot和directlabels包实现的。谢谢你,你能解释一下这些数字(标签)到底是什么意思吗?我对所有这一切都很陌生,我真的不明白,我遵循的一个教程中有他的标签词,这些词是放在这些数字类别中的吗?嗨,大卫,标签是根据您提供的代码生成的,作为m
的rownames
。这些在上面的代码中定义为rownames(m)