I am unable to colour the names of the species in my ggtree. I have consulted with previous questions such as: How to colour the tips of tree by group in ggtree?, but I am unable to apply the solution to my own problem.
Here is my minimal working code:
# Load necessary libraries
library(metacoder)
library(taxize)
library(ggtree)
library(tidyverse)
library(rentrez)
my.db<-data.frame(
ID=c(1436140, 214434, 426669, 216727, 1223577, 1752675),
Name=c("Ulnaria acus","Fragilaria pinnata","Ulnaria ulna", "Achnanthes", "Gomphonema clavatum", "Navicula cincta"),
Blocks=c("Block1","Block2", "Block3", "Block2", "Block3", "Block3"))
class<- classification(my.db$ID, db="ncbi")
class.tree<-class2tree(class, check = TRUE)
tree<-ggtree(tr= class.tree$phylo,
layout = "fan",
linewidth=0.15)+
geom_tree(linewidth=0.15)+
geom_tiplab(aes(colour=Blocks),
linewidth = 0,
size=2.5)
tree
When I run this code, I get the error:
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.
> tree
Error in `label_geom()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 5th layer.
Caused by error:
! object 'Blocks' not found
Run `rlang::last_trace()` to see where the error occurred.
When I specify geom_tiplab(aes(colour=my.db$Blocks), linewidth = 0, size=2.5)
in the code, I then get the error:
Error in `label_geom()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 5th layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (10).
✖ Fix the following mappings: `colour`.
Run `rlang::last_trace()` to see where the error occurred.
Which makes no sense as I only have 6 species in the list grouped in 3 blocks. Why would I need 10 colours?
I ran rlang::last_trace()
and got the output:
Backtrace:
▆
1. ├─base (local) `<fn>`(x)
2. └─ggplot2:::print.ggplot(x)
3. ├─ggplot2::ggplot_build(x)
4. └─ggplot2:::ggplot_build.ggplot(x)
5. └─ggplot2:::by_layer(...)
6. ├─rlang::try_fetch(...)
7. │ ├─base::tryCatch(...)
8. │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
9. │ │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
10. │ │ └─base (local) doTryCatch(return(expr), name, parentenv, handler)
11. │ └─base::withCallingHandlers(...)
12. └─ggplot2 (local) f(l = layers[[i]], d = data[[i]])
13. └─l$compute_aesthetics(d, plot)
14. └─ggplot2 (local) compute_aesthetics(..., self = self)
15. └─ggplot2:::check_aesthetics(evaled, n)