22

我正在尝试从hclust函数输出中绘制树状图。我希望树状图是水平排列的而不是默认的,可以通过(例如)

require(graphics)
hc <- hclust(dist(USArrests), "ave")
plot(hc)

我尝试使用as.dendrogram()类似的功能,plot(as.dendrogram(hc.poi),horiz=TRUE)但结果没有有意义的标签:

在此处输入图像描述

如果我使用plot(hc.poi,labels=c(...))which is without the as.dendrogram(),我可以传递labels=参数,但现在树状图是垂直的而不是水平的。有没有办法同时水平排列树状图并分配用户指定的标签?谢谢!

更新:作为 USArrests 数据集的示例,假设我想使用州名称的前两个字母的缩写作为标签,以便我想以某种方式传递labs给绘图函数:

labs = substr(rownames(USArrests),1,2)

这使

 [1] "Al" "Al" "Ar" "Ar" "Ca" "Co" "Co" "De" "Fl" "Ge" "Ha"
[12] "Id" "Il" "In" "Io" "Ka" "Ke" "Lo" "Ma" "Ma" "Ma" "Mi"
[23] "Mi" "Mi" "Mi" "Mo" "Ne" "Ne" "Ne" "Ne" "Ne" "Ne" "No"
[34] "No" "Oh" "Ok" "Or" "Pe" "Rh" "So" "So" "Te" "Te" "Ut"
[45] "Ve" "Vi" "Wa" "We" "Wi" "Wy"
4

2 回答 2

27

要在水平树状图中显示您定义的标签,一种解决方案是将数据框的行名设置为新标签(所有标签都应该是唯一的)。

require(graphics)
labs = paste("sta_",1:50,sep="") #new labels
USArrests2<-USArrests #new data frame (just to keep original unchanged)
rownames(USArrests2)<-labs #set new row names
hc <- hclust(dist(USArrests2), "ave")
par(mar=c(3,1,1,5)) 
plot(as.dendrogram(hc),horiz=T)

在此处输入图像描述

编辑 - 使用 ggplot2 的解决方案

labs = paste("sta_",1:50,sep="") #new labels
rownames(USArrests)<-labs #set new row names
hc <- hclust(dist(USArrests), "ave")

library(ggplot2)
library(ggdendro)

#convert cluster object to use with ggplot
dendr <- dendro_data(hc, type="rectangle") 

#your own labels (now rownames) are supplied in geom_text() and label=label
ggplot() + 
  geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) + 
  geom_text(data=label(dendr), aes(x=x, y=y, label=label, hjust=0), size=3) +
  coord_flip() + scale_y_reverse(expand=c(0.2, 0)) + 
  theme(axis.line.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.y=element_blank(),
        axis.title.y=element_blank(),
        panel.background=element_rect(fill="white"),
        panel.grid=element_blank())

在此处输入图像描述

于 2013-01-02T07:04:52.983 回答
27

使用dendrapply您可以根据需要自定义您的 dendro。

在此处输入图像描述

colLab <- function(n) {
  if(is.leaf(n)) {
    a <- attributes(n)
    attr(n, "label") <- substr(a$label,1,2)             #  change the node label 
    attr(n, "nodePar") <- c(a$nodePar, lab.col = 'red') #   change the node color
  }
  n
}

require(graphics)
hc <- hclust(dist(USArrests), "ave")
clusDendro <- as.dendrogram(hc)
clusDendro <- dendrapply(clusDendro, colLab)
op <- par(mar = par("mar") + c(0,0,0,2))
plot(clusDendro,horiz=T)
于 2013-01-02T08:09:17.113 回答