I'm trying to add color to the edges (lines) of a phylogeny-type plot in R using the plot.phylo command from the ape package. This example is for a "fan" type plot, though I expect the approach would be the same with a "phylogram type" or whatever.
library('ape')
hc <- hclust(dist(USArrests), "ave")
plot(as.phylo(hc), type="fan")
Adding colour to the tips (labels) based on a set of groups is no problem with the tip.color option combined with cutree command.
hc.cuts <- cutree(hc, k=5)
plot(as.phylo(hc), type="fan", tip.color=rainbow(5)[hc.cuts])
The edge.color option defines the colors of the edges, but not in a logincal manner when many colours are desired.
plot(as.phylo(hc), type="fan", tip.color=rainbow(5)[hc.cuts], edge.color=rainbow(5)[hc.cuts])
However, I would like the edges to match the terminal tip colours once that branch of the dendrogram is destined for a given group. In the given example, towards the red & blue groups, the first levels of edges would stay black (as it's headed for two groups: red and blue), but edges beyond this would be colored the same as the eventual tip color.
I suspect the key lies in figuring out the ordering of the $edge values in the as.phylo object, but I can't figure it myself. Thanks.
As @maj suggested in a comment, dendextend can help you out if you don't mind using that package. It is very flexible and has extensive documentation and vignettes.
Here's an example minimally adapted from the dendextend FAQ.
# install.packages("dendextend")
# install.packages("circlize")
library(dendextend)
library(circlize)
hc <- hclust(dist(USArrests))
dend <- as.dendrogram(hc)
num_clades <- 5
dend <- dend %>%
color_branches(k=num_clades, col=rainbow) %>%
color_labels(k=num_clades, col=rainbow)
par(mar = rep(0, 4))
circlize_dendrogram(dend, dend_track_height = 0.8)
It outputs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With