我试图通过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[]
包中的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
答案 0 :(得分:0)
您应首先从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`))