我遇到了this interesting website,想到了一种可视化聚类算法“Clustergram”的方法:
alt text http://www.schonlau.net/images/clustergramexample.gif
我不确定这有多么有用,但为了玩它我想用R重现它,但我不知道该怎么做。
您如何为每个项目创建一条线,以便在不同数量的集群中保持一致?
以下是可能的答案所使用的示例代码/数据:
hc <- hclust(dist(USArrests), "ave")
plot(hc)
答案 0 :(得分:9)
更新:我发布了一个解决方案,其中包含一个冗长的示例和讨论here。 (它基于我给出的代码)。此外,Hadley非常友好,并提供了代码的ggplot2实现。
这是一个基本的解决方案(更好的一个,看看上面的“更新”):
set.seed(100)
Data <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(Data) <- c("x", "y")
# noise <- runif(100,0,.05)
line.width <- rep(.004, dim(Data)[1])
Y <- NULL
X <- NULL
k.range <- 2:10
plot(0, 0, col = "white", xlim = c(1,10), ylim = c(-.5,1.6),
xlab = "Number of clusters", ylab = "Clusters means",
main = "(Basic) Clustergram")
axis(side =1, at = k.range)
abline(v = k.range, col = "grey")
centers.points <- list()
for(k in k.range){
cl <- kmeans(Data, k)
clusters.vec <- cl$cluster
the.centers <- apply(cl$centers,1, mean)
noise <- unlist(tapply(line.width, clusters.vec,
cumsum))[order(seq_along(clusters.vec)[order(clusters.vec)])]
noise <- noise - mean(range(noise))
y <- the.centers[clusters.vec] + noise
Y <- cbind(Y, y)
x <- rep(k, length(y))
X <- cbind(X, x)
centers.points[[k]] <- data.frame(y = the.centers , x = rep(k , k))
# points(the.centers ~ rep(k , k), pch = 19, col = "red", cex = 1.5)
}
require(colorspace)
COL <- rainbow_hcl(100)
matlines(t(X), t(Y), pch = 19, col = COL, lty = 1, lwd = 1.5)
# add points
lapply(centers.points,
function(xx){ with(xx,points(y~x, pch = 19, col = "red", cex = 1.3)) })