5

我在树状图中为叶子着色如下

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)创建一个具有鲜明对比的调色板当树状图中有许多叶子和颜色时,颜色(彩虹,heat.colors 等似乎都融合在一起了。

任何意见是极大的赞赏 !

4

2 回答 2

6

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

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() 

在此处输入图像描述

于 2012-08-15T11:48:02.440 回答
4
  1. 利用legend()

    cols <- c("orange","forestgreen")
    legend("topright", legend = c("North","South"),
           fill = cols, border = cols, bty = "n")
    
  2. 我不相信你可以,stats:::plot.dendrogram()因为标签是用绘制的text()并且图形参数没有传递给该函数,所以没有黑客攻击。中的相关代码stats:::plot.dendrogram()为:

    if (!is.null(et <- attr(x, "edgetext"))) {
        my <- mean(hgt, yTop)
        if (horiz) 
            text(my, x0, et)
        else text(x0, my, et)
    }
    

    将整个函数源复制到编辑器中并对其进行编辑以执行您想要的操作,然后将其分配给您自己的函数对象并使用它。如果它因为找不到函数而失败(它们可能未从命名空间中导出,请找出它是哪个命名空间,并ns:::ns有问题的函数前面加上相关的命名空间。

  3. 尝试使用RColorBrewer包来选择分类调色板。

于 2012-08-15T11:29:45.950 回答