❝本节来如何通过R代码多层次网络图,在以往代码的基础上叠加部分内容。有此需求的朋友可以参考使用,整个过程仅参考。希望对各位观众老爷能有所帮助。❞
library(tidyverse)
library(janitor)
library(tidygraph)
library(ggraph)
library(ggtext)
library(readxl)
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)
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
)
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)
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))
graph <- igraph::graph_from_data_frame(edges, vertices = nodes)
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())