代码语言:javascript复制❝本节来如何通过R代码多层次网络图,在以往代码的基础上叠加部分内容。有此需求的朋友可以参考使用,整个过程仅参考。希望对各位观众老爷能有所帮助。❞
library(tidyverse)
library(janitor)
library(tidygraph)
library(ggraph)
library(ggtext)
library(readxl)
导入数据
代码语言:javascript复制sharks <- read_excel("data.xlsx") %>%
clean_names() %>%
select(superorder = superorder_sharks_and_rays_subclass_chimaera,
order, family, genus, species) %>%
mutate(species = paste(genus, species)) %>%
sample_frac(0.1)
构建边文件
代码语言:javascript复制origin_superorder_connections <-
tibble(from = "origin",to = unique(sharks$superorder))
superorder_order_connections <-
sharks %>% distinct(from = superorder, to = order)
order_family_connections <-
sharks %>% distinct(from = order, to = family)
family_genus_connections <-
sharks %>% distinct(from = family, to = genus)
genus_species_connections <-
sharks %>% distinct(from = genus, to = species)
edges <- bind_rows(
superorder_order_connections,
order_family_connections,
family_genus_connections,
genus_species_connections,
origin_superorder_connections
)
构建点文件
代码语言:javascript复制nodes <- distinct(edges, name = to, group = from) %>%
mutate(
is_main = !str_detect(name, "\ "),
label = ifelse(is_main, name, NA)) %>%
add_row(name = "origin", is_main = FALSE) %>%
arrange(group, name)
构建文本角度
代码语言:javascript复制nodes$id <- NA
is_leaf <- nodes$group != "origin" & nodes$name != "origin"
is_leaf <- nodes$group != "origin" & nodes$name != "origin"
nleaves <- nrow(nodes[is_leaf, ])
nodes$id[is_leaf] <- seq_len(nleaves)
nodes$angle <- 90 - 360 * nodes$id / nleaves
nodes$hjust <- ifelse(nodes$angle < -90, 1, 0)
nodes$angle <- ifelse(nodes$angle < -90, nodes$angle 180, nodes$angle)
nodes <- nodes %>% mutate(angle = replace_na(angle, 0),
hjust = replace_na(hjust, 0))
整合边点文件
代码语言:javascript复制graph <- igraph::graph_from_data_frame(edges, vertices = nodes)
绘制网络图
代码语言:javascript复制ggraph(graph, layout = "dendrogram", circular = TRUE)
geom_node_point(aes(fill = group,color=group),shape = 21, stroke = NA,
show.legend = F)
geom_edge_diagonal(color = "#00A08A",edge_width = 0.1)
geom_node_text(aes(label = label),check_overlap = TRUE,size = 3,color = "black")
guides(fill = "none", size = "none")
theme(plot.margin = margin(b=3,t=3,r=3,l=3),
legend.position = "none",
plot.background =element_blank(),
panel.background = element_blank())