jamesbang

V1

2022/10/29阅读：44主题：雁栖湖

# 🤣 NetworkD3 | 让我们一起画个动态的桑基图吧~

## 2用到的包

``rm(list = ls())library(tidyverse)library(visNetwork)library(networkD3)library(igraph)``

## 3示例数据

``letters <- read.csv("correspondence-data-1585.csv")``

## 4整理nodes数据

``sources <- letters %>%  distinct(source) %>%  rename(label = source)destinations <- letters %>%  distinct(destination) %>%  rename(label = destination)nodes <- full_join(sources, destinations, by = "label")%>%   rowid_to_column("id")``

## 5整理edges数据

``edges <- letters %>%    group_by(source, destination) %>%   summarise(weight = n()) %>%   ungroup() %>%   left_join(nodes, by = c("source" = "label")) %>%   rename(from = id) %>%   left_join(nodes, by = c("destination" = "label")) %>%   rename(to = id)edges <- edges %>%   dplyr::select(., from, to, weight)``

## 6进一步整理数据

Note! 这里需要注意的是，`networkD3`输入文件的`ID`需要从`0`开始计数。🫠

``nodes_d3 <- mutate(nodes, id = id - 1)edges_d3 <- mutate(edges, from = from - 1, to = to - 1)``

## 7桑基图

``sankeyNetwork(Links = edges_d3, Nodes = nodes_d3, Source = "from", Target = "to",               NodeID = "label", Value = "weight", fontSize = 16, unit = "Letter(s)")``

##### jamesbang
V1

wx🔍: Grassssss 卷起来了