欢迎关注R语言数据分析指南
❝最近VIP交流群中有朋友询问一张桑基图的画法,目前在R中绘制桑基图的包主要使用「ggsankey」来实现,但是此图由于是交互式因此可见是由「networkD3」包绘制而成,下面就来通过一个小案例介绍如何使用「networkD3」包来绘制一个交互式的桑基图。 ❞
加载R包
代码语言:javascript复制library(tidyverse)
install.packages("networkD3")
library(networkD3)
导入数据
代码语言:javascript复制refresults <- read.csv("result-data.csv")
数据清洗
代码语言:javascript复制# 按地区分组进行计算
results <- refresults %>%
group_by(Region) %>%
summarise(Remain = sum(Remain), Leave = sum(Leave)) %>%
pivot_longer(-Region, names_to = "result", values_to = "vote")
构建节点数据
代码语言:javascript复制regions <- unique(results$Region)
nodes <- data.frame(node = 0:13, name = c(regions, "Leave", "Remain"))
合并结果和节点数据
代码语言:javascript复制results <- results %>%
inner_join(nodes, by = c("Region" = "name")) %>%
inner_join(nodes, by = c("result" = "name")) %>%
rename(source = node.x, target = node.y, value = vote)
创建链接数据
代码语言:javascript复制links <- results[, c("source", "target", "value")]
绘制交互式桑基图
代码语言:javascript复制sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
units = "votes")