Change Dendrogram leaves

后端 未结 3 1191
醉话见心
醉话见心 2020-12-15 12:45

I want to modify the properties of the leaves in a dendrogram produced from plot of an hclust object. Minimally, I want to change the colors, but any help you can provide w

3条回答
  •  借酒劲吻你
    2020-12-15 13:20

    It is not clear what you want to use it for, but I often need to identify a branch in a dendrogram. I've hacked the rect.hclust method to add a density and label input.

    You would call it like this:

    
    k <- 3 # number of branches to identify
    labels.to.identify <- c('1','2','3')
    required.density <- 10 # the density of shading lines, in lines per inch 
    rect.hclust.nice(tree, k, labels=labels.to.identify, density=density.required)

    Here is the function

    
    
    rect.hclust.nice = function (tree, k = NULL, which = NULL, x = NULL, h = NULL, border = 2, 
        cluster = NULL,  density = NULL,labels = NULL, ...) 
    {
        if (length(h) > 1 | length(k) > 1) 
            stop("'k' and 'h' must be a scalar")
        if (!is.null(h)) {
            if (!is.null(k)) 
                stop("specify exactly one of 'k' and 'h'")
            k <- min(which(rev(tree$height) < h))
            k <- max(k, 2)
        }
        else if (is.null(k)) 
            stop("specify exactly one of 'k' and 'h'")
        if (k < 2 | k > length(tree$height)) 
            stop(gettextf("k must be between 2 and %d", length(tree$height)), 
                domain = NA)
        if (is.null(cluster)) 
            cluster <- cutree(tree, k = k)
        clustab <- table(cluster)[unique(cluster[tree$order])]
        m <- c(0, cumsum(clustab))
        if (!is.null(x)) {
            if (!is.null(which)) 
                stop("specify exactly one of 'which' and 'x'")
            which <- x
            for (n in 1L:length(x)) which[n] <- max(which(m < x[n]))
        }
        else if (is.null(which)) 
            which <- 1L:k
        if (any(which > k)) 
            stop(gettextf("all elements of 'which' must be between 1 and %d", 
                k), domain = NA)
        border <- rep(border, length.out = length(which))
        labels <- rep(labels, length.out = length(which))
        retval <- list()
        for (n in 1L:length(which)) {
            rect(m[which[n]] + 0.66, par("usr")[3L], m[which[n] + 
                1] + 0.33, mean(rev(tree$height)[(k - 1):k]), border = border[n], col = border[n], density = density, ...)
            text((m[which[n]] + m[which[n] + 1]+1)/2, grconvertY(grconvertY(par("usr")[3L],"user","ndc")+0.02,"ndc","user"),labels[n])
            retval[[n]] <- which(cluster == as.integer(names(clustab)[which[n]]))
        }
        invisible(retval)
    }
    

提交回复
热议问题