【问题标题】:How do I add string variables to a dendrogram with labels coloured by factor level?如何将字符串变量添加到带有按因子级别着色的标签的树状图中?
【发布时间】:2018-11-26 17:21:26
【问题描述】:

this question 的答案之一是对 iris 数据集子集的树状图标签进行颜色编码。我想做的是保留标签的字符串名称,以便他们会说 setosa、virginica 等以及它们的颜色。

这是代码

# install.packages("dendextend")
library(dendextend)

small_iris <- iris[c(1, 51, 101, 2, 52, 102), ]
dend <- as.dendrogram(hclust(dist(small_iris[,-5])))
# Like: 
# dend <- small_iris[,-5] %>% dist %>% hclust %>% as.dendrogram

# By default, the dend has no colors to the labels
labels_colors(dend)
par(mfrow = c(1,2))
plot(dend, main = "Original dend")

# let's add some color:
colors_to_use <- as.numeric(small_iris[,5])
colors_to_use
# But sort them based on their order in dend:
colors_to_use <- colors_to_use[order.dendrogram(dend)]
colors_to_use
# Now we can use them
labels_colors(dend) <- colors_to_use
# Now each state has a color
labels_colors(dend) 
plot(dend, main = "A color for every Species")

【问题讨论】:

    标签: r cluster-analysis dendrogram dendextend


    【解决方案1】:

    您需要在绘图前更新标签。例如使用labels(dend) &lt;- small_iris[,5][order.dendrogram(dend)]

    完整代码和输出:

    # install.packages("dendextend")
    library(dendextend)
    
    small_iris <- iris[c(1, 51, 101, 2, 52, 102), ]
    dend <- as.dendrogram(hclust(dist(small_iris[,-5])))
    # Like: 
    # dend <- small_iris[,-5] %>% dist %>% hclust %>% as.dendrogram
    
    # By default, the dend has no colors to the labels
    labels_colors(dend)
    par(mfrow = c(1,2))
    plot(dend, main = "Original dend")
    
    # let's add some color:
    colors_to_use <- as.numeric(small_iris[,5])
    colors_to_use
    # But sort them based on their order in dend:
    colors_to_use <- colors_to_use[order.dendrogram(dend)]
    colors_to_use
    # Now we can use them
    labels_colors(dend) <- colors_to_use
    # Now each state has a color
    labels_colors(dend) 
    
    ### UPDATE <--------------------------------
    labels(dend) <- small_iris[,5][order.dendrogram(dend)]
    
    
    plot(dend, main = "A color for every Species")
    

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2015-09-04
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 2020-10-06
      • 2023-03-12
      相关资源
      最近更新 更多