【问题标题】:DBSCAN clustering plotting through ggplot2通过 ggplot2 进行 DBSCAN 聚类绘图
【发布时间】:2023-04-07 07:00:02
【问题描述】:

我正在尝试通过 ggplot2 绘制 dbscan 聚类结果。如果我理解正确,当前的 dbscan 会使用基本绘图功能以黑色绘制噪声。先上一些代码,

library(dbscan)
n <- 100
x <- cbind(
  x = runif(5, 0, 10) + rnorm(n, sd = 0.2),
  y = runif(5, 0, 10) + rnorm(n, sd = 0.2)
)
plot(x)
kNNdistplot(x, k = 5)
abline(h=.25, col = "red", lty=2)

res <- dbscan::dbscan(x, eps = .25, minPts = 4)

plot(res, x, main = "DBSCAN")
x <- data.frame(x)
ggplot(x, aes(x = x, y=y)) + geom_point(color = res$cluster+1,  pch = clusym[res$cluster+1]) 
+ theme_grey() +  ggtitle("(c)") + labs(x ="x", y = "y") 

我想在这里做两件不同的事情,首先尝试通过ggplot() 绘制聚类输出。困难在于,如果我使用res$cluster 来绘制点,plot() 将忽略带有 0 个标签的点(它们是噪声点),并且ggplots() 会出现错误,因为res$cluster 的长度将小于要绘制的实际数据如果我尝试使用res$cluster+1,它会给噪声点1,这是我不想要的。其次,如果可能的话,尝试做一些 clusym[] in package fpc 所做的事情。它绘制标签为 1、2、3、... 的集群并忽略 0 个标签。如果我的噪声点标签仍然为 0,然后给任何特定符号说“*”到具有特定颜色的噪声点,那很好,让我们说灰色。我看到了一个堆栈溢出帖子,它试图为凸包绘图做类似的事情,但如果我不想绘制外壳并想要每个集群的聚类数,我仍然无法弄清楚如何做到这一点。 我认为的一种可能性是首先绘制没有噪声的点,然后在原始绘图中额外添加具有所需颜色和符号的噪声点。 但由于 res$cluster 长度不等于 x,因此出现错误。

ggplot(x, aes(x = x, y=y)) + geom_point(color = res$cluster+1,  pch = clusym[res$cluster+1]) 
+ theme_grey() +  ggtitle("(c)") + labs(x ="x", y = "y") + adding noise points

Error: Aesthetics must be either length 1 or the same as the data (100): shape, colour

【问题讨论】:

    标签: r plot ggplot2 cluster-analysis dbscan


    【解决方案1】:

    您应该首先将 DBSCAN 输出中的第三列作为子集,将其作为新列(即作为集群)附加到原始数据上,并将其分配为一个因素。

    当您制作 ggplot 时,您可以为集群分配颜色或形状。至于忽略噪声点,我会这样做。

    data <- dataframe with the cluster column (still in numeric form).
    data2 <- dplyr::filter(data, cluster > 0)
    data2$cluster <- as.factor(data2$cluster)
    ggplot(data2, aes(x = x, y = y) +
        geom_point(aes(color = `cluster`))
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 2016-11-24
      • 2021-10-19
      • 2020-07-29
      • 2012-06-13
      • 2015-07-20
      • 2012-12-01
      • 2014-07-24
      • 2017-05-17
      相关资源
      最近更新 更多