【问题标题】:ggplot2 and ggdendro - plotting color bars under the node leavesggplot2 和 ggdendro - 在节点叶子下绘制颜色条
【发布时间】:2013-11-24 10:56:03
【问题描述】:

目前我正在使用ggplot2ggdendro 绘制树状图。但是现在我需要在叶子下绘制一个离散变量以及标签。

例如,在一篇出版物(Zhang et al., 2006)中,我看到了这样的树状图(注意叶子标签下的颜色条):

我有兴趣使用我已经分箱的数据对 ggdendro + ggplot2 做同样的事情。这可能吗?

【问题讨论】:

    标签: r plot ggplot2 ggdendro


    【解决方案1】:

    首先,您需要为彩条制作数据框。例如,我使用数据USArrests - 使用hclust() 函数进行聚类并保存对象。然后使用此聚类对象使用函数cutree() 将其划分为簇并保存为列簇。列states 包含聚类对象hc 的标签,该对象的级别与hc 的输出中的顺序相同。

    library(ggdendro)
    library(ggplot2)
    hc <- hclust(dist(USArrests), "ave")
    df2<-data.frame(cluster=cutree(hc,6),states=factor(hc$labels,levels=hc$labels[hc$order]))
    head(df2)
               cluster     states
    Alabama          1    Alabama
    Alaska           1     Alaska
    Arizona          1    Arizona
    Arkansas         2   Arkansas
    California       1 California
    Colorado         2   Colorado
    

    现在将两个图另存为对象 - 使用 geom_tile() 制作的树状图和颜色条,使用 states 作为 x 值,cluster 数字作为颜色。格式化完成以删除所有轴。

    p1<-ggdendrogram(hc, rotate=FALSE)
    
    
    p2<-ggplot(df2,aes(states,y=1,fill=factor(cluster)))+geom_tile()+
      scale_y_continuous(expand=c(0,0))+
      theme(axis.title=element_blank(),
            axis.ticks=element_blank(),
            axis.text=element_blank(),
            legend.position="none")
    

    现在您可以使用@Baptiste 对this question 的回答来对齐两个图。

    library(gridExtra)
    
    gp1<-ggplotGrob(p1)
    gp2<-ggplotGrob(p2)  
    
    maxWidth = grid::unit.pmax(gp1$widths[2:5], gp2$widths[2:5])
    gp1$widths[2:5] <- as.list(maxWidth)
    gp2$widths[2:5] <- as.list(maxWidth)
    
    grid.arrange(gp1, gp2, ncol=1,heights=c(4/5,1/5))
    

    【讨论】:

      猜你喜欢
      • 2011-12-24
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2023-03-12
      • 2018-11-16
      • 2013-02-07
      相关资源
      最近更新 更多