大数跨境
0
0

R语言ggtree给树节点添加饼图注释

R语言ggtree给树节点添加饼图注释 小明的数据分析笔记本
2024-12-11
0

ggtree 的文档链接

https://yulab-smu.top/treedata-book/index.html

节点添加饼图的代码

https://yulab-smu.top/treedata-book/chapter8.html

模拟一个简单的进化树

library(ggtree)
tree<-rtree(5)
ggtree(tree)+
geom_tiplab()

每个节点都有一个数字对应,我们可以把数字显示到图上

ggtree(tree)+
geom_nodelab(aes(label=node))+
geom_tiplab(aes(label=node))

现在假如我要给1 2 3 4 5 节点添加饼图

nodepie函数可以批量做饼图,数据格式如下

node.pie.dat.01<-data.frame(node=1:5,
col1=6:10,
col2=8:12)

node.pie.dat.01

饼图代码

node.pie.list.01<-nodepie(node.pie.dat.01,cols = 2:3)

输出是一个列表,批量改配色代码

cols<-c("red","blue")
lapply(node.pie.list.01, function(g) g+scale_fill_manual(values = cols))

把饼图添加到树图上

ggtree(tree) +
geom_inset(node.pie.list.01,width = 0.1,height = 0.1)

但是树的布局如果改成了环形会报错

Error in `annotation_custom()`:
! Problem while converting geom to grob.
i Error occurred in the 3rd layer.
Caused by error in `draw_panel()`:
! `annotation_custom()` only works with `coord_cartesian()`.

在ggtree 的github主页上的issue里有人给出了解决办法,是使用ggpp包中的geom_plot()函数来做

https://github.com/YuLab-SMU/ggtree/issues/419

df.pie<-tibble::tibble(node=names(node.pie.list.01) %>% as.numeric(),
pies=node.pie.list.01)

library(ggpp)
ggtree(tree,layout = "circular",branch.length = "none") %<+%
df.pie +
geom_plot(data = td_filter(isTip),
aes(x=x,y=y,label=pies),
vp.width=0.09,vp.height=0.09,hjust=0.5,vjust=0.5)

这个我试了一下,数据如果比较多的话有时候饼图的位置会有些偏移,暂时不知道是什么原因

欢迎大家关注我的公众号

小明的数据分析笔记本

小明的数据分析笔记本 公众号 主要分享:1、R语言和python做数据分析和数据可视化的简单小例子;2、园艺植物相关转录组学、基因组学、群体遗传学文献阅读笔记;3、生物信息学入门学习资料及自己的学习笔记!


【声明】内容源于网络
0
0
小明的数据分析笔记本
分享R语言和python在生物信息领域做数据分析和数据可视化的简单小例子;偶尔会分享一些组学数据处理相关的内容
内容 971
粉丝 0
小明的数据分析笔记本 分享R语言和python在生物信息领域做数据分析和数据可视化的简单小例子;偶尔会分享一些组学数据处理相关的内容
总阅读127
粉丝0
内容971