如何在ggtree/ggplot2中通过geom_line按预定义组为分类群线条着色
按预定义组为系统发育树连接线条着色
你需要从末端标签的前缀(如G1、G2)提取分组信息,以此为连接线条着色。核心修改是在数据处理阶段新增分组列,再将该列映射到颜色参数。
完整修改代码
library(ape) library(tidytree) library(phytools) library(dplyr) library(ggtree) library(ggplot2) library(stringr) # 新增字符串处理包 # 读取并根化树文件 noroot_tree1 <- read.tree("1_HAgenotyping.aln.fasta.treefile.nwk") noroot_tree2 <- read.tree("8_NAgenotyping.aln.fasta.treefile.nwk") noroot_tree3 <- read.tree("7_NSgenotyping.aln.fasta.treefile.nwk") x <- midpoint.root(noroot_tree1) y <- midpoint.root(noroot_tree2) z <- midpoint_root(noroot_tree3) # 初始化树绘图数据 p1 <- ggtree(x) d1 <- p1$data d2 <- fortify(y) d3 <- fortify(z) # 调整树的x轴位置,避免重叠 d2$x <- d2$x + max(d1$x) + 1 d3$x <- d3$x + max(d2$x) + 1 # 合并末端标签数据并提取分组 dd = bind_rows(d1, d2, d3) %>% filter(!is.na(label)) %>% mutate( # 从标签前缀提取分组(匹配G开头加数字的格式) group = str_extract(label, "^G\\d+") ) # 绘图:用group列控制线条颜色 p1 + geom_tree(data = d2) + geom_tree(data = d3) + geom_line(aes(x, y, group=label, color=group), data=dd, alpha=.3) + scale_color_manual(values = c("G1" = "red", "G2" = "blue")) # 可自定义组颜色
关键说明
- 用
str_extract(label, "^G\\d+")精准提取标签开头的G1、G2等分组标识;如果仅需区分G1/G2两组,也可以用ifelse(str_starts(label, "G1|"), "G1", "G2")实现。 - 将
geom_line中的color=node替换为color=group,让线条颜色与分组绑定。 - 通过
scale_color_manual可自定义各组颜色,按需调整参数即可。
内容的提问来源于stack exchange,提问作者bmolle
相关产品推荐
相关产品推荐

