代码之家  ›  专栏  ›  技术社区  ›  Tal Galili

如何创建“聚类图”图((右)

  •  7
  • Tal Galili  · 技术社区  · 15 年前

    我遇到了 this interesting website ,提出了一种可视化聚类算法“Clustergram”的方法:

    alt text
    schonlau.net

    我不知道这到底有多有用,但为了玩它,我想用R来复制它,但不知道如何去做它。

    如何为每个项目创建一行,以便在不同数量的集群中保持一致?

    下面是一个示例代码/数据,可供选择:

    hc <- hclust(dist(USArrests), "ave")
    plot(hc)
    
    1 回复  |  直到 5 年前
        1
  •  9
  •   gung - Reinstate Monica    10 年前

    更新 :我发布了一个带有冗长示例和讨论的解决方案 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)) })
    

    enter image description here