水平树状图中的R用标签(horizontal dendrogram in R with labels

2019-07-17 18:27发布

我想画从一个树状hclust功能输出。 希望树形水平布置,而不是默认,其可以是通过获得(例如)

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

我试图用as.dendrogram()函数像plot(as.dendrogram(hc.poi),horiz=TRUE)但结果是没有意义的标签:

如果我用plot(hc.poi,labels=c(...))它是没有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"

Answer 1:

为了显示水平树状你定义的标签,一种解决方案是设置数据帧新的标签的行名(所有标签应该是唯一的)。

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



Answer 2:

使用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)


文章来源: horizontal dendrogram in R with labels