我按照树状图对叶子进行了着色,如下所示

require(graphics)

dm <- hclust(dist(USArrests[1:5,]), "ave")

df<-data.frame("State"=c("Alabama","Alaska","Arizona","Arkansas","California"),   "Location"=c("South","North","West","South","West"))


color.sites<-function(dm){
    dend<-as.dendrogram(dm)
    plot(dend)

    cols <- attributes(dend)
    df$ColorGroups <- factor(df$Location)

    #Set colour pallette
    Location.Pal <- rainbow(nlevels(df$ColorGroups), s=0.9,v=0.9,start=0.1,end=0.9,alpha=1)

    colorleaves <- function (n) {
    # only apply to "leaves" in other words the labels
    if(is.leaf(n)) {
        i <- which(df$State == attr(n,"label"))
        col.lab  <- Location.Pal[[unclass(df$ColorGroups[[i]])]]
        a <- attributes(n)
        attr(n, "nodePar") <- c(a$nodePar, list(lab.col = col.lab))
    }
    n
}

xx <- dendrapply(dend, colorleaves)

plot(xx, cex=3, cex.main=2, cex.lab=5, cex.axis=1, mar=c(3,3,3,3), main="Title")
}

color.sites(dm)

我想:
1)添加说明颜色的图例(例如,橙色=北)
2)使叶子标签更大和更大胆(cex.lab似乎不起作用)
3)创建一个具有强烈对比色的调色板(彩虹色,热色等,当树状图中有很多叶子和颜色时,所有这些似乎都融合在一起了)。

任何意见是极大的赞赏 !

最佳答案

如果您已经知道如何使用和调整ggplot2图形,则另一个解决方案是使用@Andrie ggdendro package

library(ggplot2)
library(ggdendro)

dm <- hclust(dist(USArrests[1:5,]), "ave")

df <- data.frame(State = c("Alabama","Alaska","Arizona","Arkansas","California"),
                 Location = c("South","North","West","South","West"))


hcdata<- dendro_data(dm, type="rectangle")

hcdata$labels <- merge(x = hcdata$labels, y = df,  by.x = "label", by.y = "State")


ggplot() +
 geom_segment(data=segment(hcdata), aes(x=x, y=y, xend=xend, yend=yend)) +
 geom_text(data = label(hcdata), aes(x=x, y=y, label=label, colour = Location, hjust=0), size=3) +
 geom_point(data = label(hcdata), aes(x=x, y=y), size=3, shape = 21) +
 coord_flip() +
 scale_y_reverse(expand=c(0.2, 0)) +
 scale_colour_brewer(palette = "Dark2") +
 theme_dendro()

关于r - 在R中为有色叶子的树状图创建图例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11967880/

10-12 17:31