欢迎关注R语言数据分析指南
本节来介绍如何使用ggraph绘制圆形网络图,这里使用了一个R包ccgraph,各位观众老爷细细体会,下面通过一个小例子来进行展示
加载R包
library(tidygraph)
library(ggraph)
library(tidyverse)
library(magrittr)
library(devtools)
library(tidytext)
library(tidygraph)
library(RColorBrewer)
安装R包
install_github("gaospecial/ccgraph")
library(ccgraph)
导入数据
otu <- read_tsv("otu_taxa_table.xls") %>%
select(OTU:C5,taxonomy) %>%
separate(taxonomy,
into=c("domain","phylum","class","order","family","genus","species"),sep=";") %>%
mutate_at(vars(c(`domain`:`species`)),~str_split(.,"__",simplify=TRUE)[,2]) %>%
column_to_rownames("OTU")
table <- otu %>% select_if(~is.numeric(.)) %>% rownames_to_column("ID")
tax <- otu %>% select_if(~!is.numeric(.)) %>% rownames_to_column("ID")
数据清洗
title_description_tf_idf <- table %>% left_join(.,tax %>% select(1,phylum),by="ID") %>%
select(-ID) %>%
group_by(phylum) %>%
summarise(across(where(is.numeric), ~ sum(.x, na.rm=TRUE))) %>%
pivot_longer(-phylum) %>%
filter(phylum!="",value!=0) %>%
set_colnames(c("title","word","n")) %>%
bind_tf_idf(word, title , n)
生成边文件&点文件
title_description_tf_idf
country_index <- c("title","word")
nodes_country <- gather_graph_node(title_description_tf_idf ,index = country_index, value = "n",root="phylum")
edges_country <- gather_graph_edge(title_description_tf_idf ,index = country_index,root="phylum")
数据整合
graph_country <- tbl_graph(nodes_country,edges_country)
数据可视化
ggraph(graph_country,layout = 'dendrogram', circular = TRUE) +
geom_edge_diagonal(aes(color=node1.node.branch),alpha=1/3) +
geom_node_point(aes(size=node.size,color=node.branch),alpha=1/3) +
coord_fixed()+
theme_void()+
theme(legend.position = "none")+
scale_size(range = c(0.5,80)) +
geom_node_text(aes(x = 1.0175 * x,y = 1.0175 * y,
label = node.short_name,
angle = -((-node_angle(x, y) + 90) %% 180) + 90,
filter = leaf,color = node.branch), size =3, hjust = 'outward') +
scale_colour_manual(values= rep( brewer.pal(9,"Paired") , 30))+
geom_node_text(aes(label=node.short_name,filter = !leaf,color = node.branch),
fontface="bold",size=4,family="Times")
数据获取
本节内容到此结束,喜欢的小伙伴欢迎分享转发,评论区留言交流可获取数据
网友评论