R:在图的顶部叠加聚类 [英] R: Superimpose Clusters on top of a Graph
问题描述
我正在使用R编程语言.我创建了一些数据,并为此数据制作了KNN图.然后,我对该图进行了聚类.现在,我想将聚类叠加在图的顶部.
这是我编造的一个示例(来源:
现在,我执行聚类算法:
x = bJP_R<-function(x,k,kt){# 步骤1nn<-kNN(x,k,sort = FALSE)$ idn<-nrow(nn)# 第2步标签<-1:n#步骤3for(i在1:n中){#检查i的所有邻居for(j in nn [i,]){如果(j< i)下一个###我们已经检查了该边缘if(labels [i] == labels [j])下一个###已在同一群集中if(i%in%nn [j,]&&length(intersect(nn [i,],nn [j,]))+ 1L> = kt){标签[标签==最大值(标签[i],标签[j])]<-分钟(标签[i],标签[j])}}}#步骤4:创建连续标签as.integer(factor(labels))}cl<-JP_R(x,k = 10,kt = 6)
我可以对这种聚类算法做出基本说明:
plot(x,col = cl)
但是有没有办法在第一张图像上显示这些簇?
像这样吗?
谢谢
您可以使用任何一个
points(x,col = cl)
或
par(new = TRUE)情节(x,col = cl)
I am using the R programming language. I created some data and make a KNN graph of this data. Then I performed clustering on this graph. Now, I want to superimpose the clusters on top of the graph.
Here is an example I made up (source: https://michael.hahsler.net/SMU/EMIS8331/material/jpclust.html) - suppose we have a dataset with 3 variables : the longitude of the house, the latitude of the house and the price of the house (we "scale" all these variables since the "price" and the "long/lat" are in different units). We can then make a KNN graph (using R software):
library(dbscan)
plot_nn <- function(x, nn, ...) {
plot(x, ...)
for(i in 1:nrow(nn$id))
for(j in 1:length(nn$id[i,]))
lines(x = c(x[i,1], x[nn$id[i,j],1]), y = c(x[i,2], x[nn$id[i,j],2]))
}
Lat = round(runif(500,43,44), 4)
Long = round(runif(500,79,80), 4)
price = rnorm(500,1000000,200)
b = data.frame(Lat, Long, price)
b = scale(b)
b = as.matrix(b)
nn <- kNN(b, k = 10, sort = FALSE)
plot_nn(b, nn, col = "grey")
Now, I perform the clustering algorithm:
x = b
JP_R <- function(x, k, kt) {
# Step 1
nn <- kNN(x, k, sort = FALSE)$id
n <- nrow(nn)
# Step 2
labels <- 1:n
# Step 3
for(i in 1:n) {
# check all neighbors of i
for(j in nn[i,]) {
if(j<i) next ### we already checked this edge
if(labels[i] == labels[j]) next ### already in the same cluster
if(i %in% nn[j,] && length(intersect(nn[i,], nn[j,]))+1L >= kt) {
labels[labels == max(labels[i], labels[j])] <- min(labels[i], labels[j])
}
}
}
# Step 4: create contiguous labels
as.integer(factor(labels))
}
cl <- JP_R(x, k = 10, kt = 6)
I can make a basic plot of this clustering algorithm:
plot(x, col = cl)
But is there a way to show these clusters on the first image instead?
Something like this?
Thanks
You can use either
points(x, col = cl)
or
par(new = TRUE)
plot(x, col = cl)
这篇关于R:在图的顶部叠加聚类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!