Annotate multiple labels and colors

72 views Asked by At

I am trying to annotate multiple labels with multiple colors. But when I try map it ignores if there are multiple values.

library(ggtree)
library(ggplot2)

my_tree <- rtree(5)

h = structure(list(name = c("t1", "t2", "t3"), labs = I(list(c("a1","a2","a3"),  "b1", "c3")), colors = I(list(c("red","blue","green"), "red", "green"))) ,class = "data.frame", row.names = c(NA, -3L))
 
t = ggtree(my_tree,ladderize = TRUE)
t <- t %<+% h

t + geom_tiplab(aes(subset=(grepl('',label,fixed=TRUE)==TRUE))) +
  Map(function(labs, colors) {
    geom_text(aes(x=branch, label=labs, colour = "black"), vjust=-7.1, size=3)
  }, labs = h$labs, colors = h$colors)

The above code puts all labels in red and ignores multiple labels and colors.

Code should map individual labels with corresponding colors and annotate. Can anyone help?

Update: lab column - shows individual labels, and color column has corresponding colors for each label.

Expected output: label for t1 is a1,a2,a3. a1 should be showed in red color, a2 in blue color and a3 in green color.

label for t2 is b1 this should be shown in red

label for t3 is c3 this should be shown in green

1

There are 1 answers

0
stefan On BEST ANSWER

Not familiar with ggtree but here is an option which uses ggtext::geom_richtext to add your colored labels. First step is to do some data wrangling and to create some HTML labels which could be rendered via ggtext::geom_richtext. Moreover, I dropped the Map and instead merge the dataset with the labels to the dataset provided by ggtree which allows to place the labels easily at the right branches.

library(ggtree)
library(ggplot2)
library(tidyr, warn = FALSE)
library(dplyr, warn = FALSE)
library(ggtext)

set.seed(123)

my_tree <- rtree(5)

h <- structure(list(
  name = c("t1", "t2", "t3"),
  labs = I(list(c("a1", "a2", "a3"), "b1", "c3")),
  colors = I(list(c("red", "blue", "green"), "red", "green"))
), class = "data.frame", row.names = c(NA, -3L))

h <- h |>
  tidyr::unnest_longer(c(labs, colors)) |>
  dplyr::mutate(
    labs = paste0("<span style='color: ", colors, "'>", labs, "</span>")
  ) |>
  dplyr::summarise(labs = paste0(labs, collapse = ", "), .by = "name")

ggtree(my_tree, ladderize = TRUE) +
  geom_tiplab(
    aes(subset = (grepl("", label, fixed = TRUE) == TRUE))
  ) +
  ggtext::geom_richtext(
    data = ~ h |>
      merge(.x[c("branch", "y", "label")], by.x = "name", by.y = "label"),
    aes(x = branch, label = labs),
    size = 3,
    vjust = -.25,
    fill = NA, label.size = NA
  )