title: Label and color leaf dendrogram (phylogeny) in R using ape package
body: <p>Following a previous post (<a href="https://stackoverflow.com/questions/18802519/label-and-color-leaf-dendrogram-in-r">Label and color leaf dendrogram in r</a>) I have a follow-up question.</p>
  
  <p>My questions are similar to the post mentioned but I wonder can it be done using ape (e.g., <code>plot(as.phylo(fit), type="fan", labelCol)</code> as it has more type of phylogeny.</p>
  
  <p>The mentioned post questions were:</p>
  
  <ul>
  <li><p>How can I show the group codes in leaf label (instead of the sample number)?</p></li>
  <li><p>I wish to assign a color to each code group and colored the leaf label according to it (it might happen that they will not be in the same clade and by that I can find more information)?</p></li>
  </ul>
  
  <p>And the code sample is:</p>
  
  <pre><code>sample = data.frame(matrix(floor(abs(rnorm(20000)*100)),ncol=200))
  groupCodes &lt;- c(rep("A",25), rep("B",25), rep("C",25), rep("D",25))
  
  ## make unique rownames (equal rownames are not allowed)
  rownames(sample) &lt;- make.unique(groupCodes)
  
  colorCodes &lt;- c(A="red", B="green", C="blue", D="yellow")
  
  
  ## perform clustering
  distSamples &lt;- dist(sample)
  hc &lt;- hclust(distSamples)
  
  ## function to set label color
  labelCol &lt;- function(x) {
    if (is.leaf(x)) {
      ## fetch label
      label &lt;- attr(x, "label")
      code &lt;- substr(label, 1, 1)
      ## use the following line to reset the label to one letter code
      # attr(x, "label") &lt;- code
      attr(x, "nodePar") &lt;- list(lab.col=colorCodes[code])
    }
    return(x)
  }
  
  ## apply labelCol on all nodes of the dendrogram
  d &lt;- dendrapply(as.dendrogram(hc), labelCol)
  
  plot(d)
  </code></pre>