无法为我的ggtree的标签提示着色

问题描述 投票:0回答:1

我无法为我的 ggtree 中的物种名称着色。我咨询过之前的问题,例如:如何在ggtree中按组为树的尖端着色?,但我无法将解决方案应用于我自己的问题。

这是我的最小工作代码:

# 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

当我运行此代码时,出现错误:

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.

当我在代码中指定

geom_tiplab(aes(colour=my.db$Blocks), linewidth = 0, size=2.5)
时,我收到错误:

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.

这毫无意义,因为列表中只有 6 个物种,分为 3 个区块。为什么我需要 10 种颜色?

我运行了

rlang::last_trace()
并得到了输出:

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)
r bioconductor ggtree
1个回答
0
投票

Blocks
变量不包含在
ggplot
的输入数据中,即在
class.tree$phylo
中。

您需要将

class.tree$phylo
加入到
my.db
。然后,您可以使用
tidytree
包格式化数据以在 ggplot 中绘图。你的情节代码有效:

library(tidytree)
x <- full_join(as_tibble(class.tree$phylo),
  my.db,
  by = c("label" = "Name")
)
tree2 <- as.treedata(x)

ggtree(
  tr = tree2,
  layout = "fan",
  linewidth = 0.15
) +
  geom_tree(linewidth = 0.15) +
  geom_tiplab(aes(colour = Blocks),
    linewidth = 0,
    size = 2.5
  )

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.