1.加载包
library("reshape2")
library(networkD3)
library(webshot)
library(tidyverse)
library(dplyr)
library(webshot)
library(htmlwidgets)
2.准备文件,一共需要2个文件。
第一个文件是你的数据文件,文件需要4列,第一列是桑吉图的左边source,第二列是画在右边的target,第三列是它们之间的值。第四列是你想要的中间连线的颜色
![](https://img.haomeiwen.com/i11134057/14b02363cc61ef41.png)
3.准备第二个文件,node文件,给每个节点一个数字编号,必须从0开始
factor_list <- sort(unique(union(data$target,data$source)))
node <- data.frame(name=c(factor_list),num_list=0:(length(factor_list)-1))
![](https://img.haomeiwen.com/i11134057/6beecbc6b66d0daa.png)
4.调整第一个文件,增加2列,把target和source的名字对应的节点编号,增加到文件中。一共6列
data<-merge(data,node,by.x="source",by.y="name",all.x=T)
data<-merge(data,node,by.x="target",by.y="name",all.x=T)
colnames(data)[5]="source2"
colnames(data)[6]="target2"
![](https://img.haomeiwen.com/i11134057/4483dc7ed762e6c5.png)
5.开始画图
test=sankeyNetwork(Links = data, Nodes = node,Source = "source_node_id", Target = "target_node_id",Value = "value", NodeID = "name",fontSize= 20, nodeWidth = 30)
saveNetwork(test, "sankey.html",selfcontained = F)
webshot("sankey.html", "sankey.pdf")
![](https://img.haomeiwen.com/i11134057/f92df444d1826795.png)
这就完成啦
网友评论