在生信分析或者一些其他的数据分析中,经常会需要绘制桑基图,在这里推荐一个非常nice的R包-sankeyD3(类似于networkD3,但是比其功能更加完善),其出的桑基图比较美观,而且自动统计相应的统计量。
https://github.com/fbreitwieser/sankeyD3
实例分析:
### 安装与加载包
install.packages("devtools")
devtools::install_github("fbreitwieser/sankeyD3")
library(sankeyD3)
然后大家需要根据自己的数据构建两个数据框:
第一个为链接数据框 links(起点、靶点、权重、链接的特征1、链接的特征1.....);
然后根据links构建第二个为节点数据框nodes(起点与靶点、点的特征1、点的特征........)
nodes <- data.frame(name=c(as.character(links$source), as.character(links$target)) %>% unique())
然后基于nodes数据框构建links中节点的唯一标识符ID,而非根据节点的name
links$IDsource <- match(links$source, nodes$name)-1
links$IDtarget <- match(links$target, nodes$name)-1
绘图
sankeyNetwork(Links = links, Nodes = nodes, Source = "IDsource", Target = "IDtarget",
Value = "weight", NodeID = "name",nodeWidth =10,units = 'TWh',
height=300,width=300,colourScale=JS("d3.scaleOrdinal(d3.schemeCategory10);"),
numberFormat=".0f",fontSize = 8)
有时候呢,我们想自己定义节点以及缎带的颜色,则可以根据几个参数来定义
nodes$color<-sample(c("red","orange","blue","green"),nrow(nodes),replace=T) #在这里进行随机自定义颜色,当然也可以按照自己的需求进行设置
sankeyNetwork(Links = links, Nodes = nodes,Source = "IDsource", Target = "IDtarget",
Value = "weight", NodeID = "name",nodeWidth =10,units = 'TWh',
height=300,width=300,numberFormat=".0f",fontSize = 8,NodeColor = "color")
也可以根据节点自定义的分类对节点进行颜色的绘制
nodes$group<-rep("水果",nrow(nodes))
nodes$group[nodes$name %in% c("上海","深圳","北京","南京")]<-"城市"
nodes$group[nodes$name %in% c("律师","老师","白领","公务员","记者","化妆师")]<-"职业"
sankeyNetwork(Links = links, Nodes = nodes,Source = "IDsource", Target = "IDtarget",
Value = "weight", NodeID = "name",nodeWidth =10,units = 'TWh',
numberFormat=".0f",fontSize = 8,height=300,width=300,
NodeGroup="group",colourScale=JS("d3.scaleOrdinal(d3.schemeCategory10);"))
对于缎带的颜色设置同理也可以对其进行分组颜色设置(这里按照其统计量进行分组设置,当然也可以按照其他进行分组)
links$group<-rep("A",nrow(links))
links$group[links$weight<500 & links$weight>=100]<-"B"
links$group[links$weight<100]<-"C"
sankeyNetwork(Links = links, Nodes = nodes,Source = "IDsource", Target = "IDtarget",
Value = "weight", NodeID = "name",nodeWidth =10,units = 'TWh',
numberFormat=".0f",fontSize = 8,height=300,width=300,
NodeGroup="group",LinkGroup = "group",
colourScale=JS("d3.scaleOrdinal(d3.schemeCategory10);"))
有时候想要缎带根据其宽度进行一定透明度的变化,可以使用 linkType="path1"参数进行设置
上面画出来的所有图片本身是不能储存为PDF文件的,只能存储为图片或者网页,为了可对其进行矢量编辑,需要进一步对sankeyNetwork函数绘制出的图形进行一定的转化
install.packages("webshot")
library(webshot)
if(!is_phantomjs_installed()){
install_phantomjs()
}
library(webshot)
p<-sankeyNetwork(Links = links, Nodes = nodes,Source = "IDsource", Target = "IDtarget",
Value = "weight", NodeID = "name",nodeWidth =10,units = 'TWh',
numberFormat=".0f",fontSize = 8,height=300,width=300,
NodeGroup="group",LinkGroup = "group",
colourScale=JS("d3.scaleOrdinal(d3.schemeCategory10);"))
### 将结果存储PDF
saveNetwork(p,"sankey.html")
webshot("sankey.html" , "sankey.pdf")