YuLab-SMU / ggtree

:christmas_tree:Visualization and annotation of phylogenetic trees
https://yulab-smu.top/treedata-book/
830 stars 172 forks source link

Unable to set colors and generate a legend for a ggtree plot based on Species #560

Open uceleste opened 1 year ago

uceleste commented 1 year ago

Hi,

I'm using the R package ggtree to plot a phylogenetic tree of 9 plant species and outgroups. I have successfully produced the phylogenetic tree I was interested in, however, I have difficulties adding a "legend". I do not receive an error message concerning the command, but the legend does not appear.

Attached is the tree I am using called "COPIA_FINAL_magg_80aa.algn.txt": COPIA_FINAL_magg_80aa.algn.txt

This is the command I'm running:

# R v4.2.2 | Rstudio 2022.12.0+353 "Elsbeth Geranium" Release (7d165dcfc1b6d300eb247738db2c7076234f6ef0, 2022-12-03) for Ubuntu Bionic

current_dir <- getwd()
setwd(current_dir)

library(ggtree)

# Load the tree
tree=read.tree("COPIA_FINAL_magg_80aa.algn.treefile")

# Set tip labels
seq=tree$tip.label
dd=data.frame(seq)
dd$Species = 0
dd$Species[grep("Balsamifera", dd$seq)]="Balsamifera"
dd$Species[grep("Deltoides", dd$seq)]="Deltoides"
dd$Species[grep("Simonii", dd$seq)]="Simonii"
dd$Species[grep("Tremula", dd$seq)]="Tremula"
dd$Species[grep("Tremuloides", dd$seq)]="Tremuloides"
dd$Species[grep("Trichocarpa", dd$seq)]="Trichocarpa"
dd$Species[grep("Nigra", dd$seq)]="Nigra"
dd$Species[grep("Purpurea", dd$seq)]="Purpurea"
dd$Species[grep("Suchowensis", dd$seq)]="Suchowensis"
dd$Species[grep("Outgroup", dd$seq)]="Outgroup"

# Set tip colors
cls=function(dd){
  ss=sort(unique(dd$Species))
  colors=setNames(palette()[1:length(ss)],ss)
  colors=colors[dd$Species]
  return(colors)
}
colors=cls(dd)

# Plot the tree
ggtree(tree) + 
  geom_tippoint(color=colors, shape=16, size=3, show.legend = TRUE) +
  geom_text2(aes(label=label, subset = !is.na(as.numeric(label)) & as.numeric(label) > 60), hjust=-0.5) +
  theme(legend.position="right")

This is the tree it generates: tree

The legend should show the names of the species associated with the colour of the tree tips. Here is an example of the tree I'm looking for. The colours don't matter, I can change them later. Do you have any suggestions? tree2

I really appreciate your assistance!