美文网首页RNA-seq
听说你的桑基图也无法保存?

听说你的桑基图也无法保存?

作者: 小洁忘了怎么分身 | 来源:发表于2021-02-08 15:35 被阅读0次

之前写过画桑基图和网络图的推文:https://www.jianshu.com/p/ff295d3444b4。今天发现,桑基图居然没办法直接保存为pdf,png这些常用的格式。搜索了一下,发现需要借助外力–webshot包。

1.画桑基图

library(tidyverse)
library(navdata)
library(networkD3)
data("phone.call2")
nodes <- phone.call2$nodes;head(nodes)
## # A tibble: 6 x 2
##      id label   
##   <int> <chr>   
## 1     1 France  
## 2     2 Belgium 
## 3     3 Germany 
## 4     4 Danemark
## 5     5 Croatia 
## 6     6 Slovenia
edges <- phone.call2$edges;head(edges)
## # A tibble: 6 x 3
##    from    to weight
##   <int> <int>  <dbl>
## 1     1     3      9
## 2     2     1      4
## 3     1     8      3
## 4     1     9      4
## 5     1    10      2
## 6     1    11      3
nodes_d3 <- mutate(nodes, id = id - 1);head(nodes_d3)
## # A tibble: 6 x 2
##      id label   
##   <dbl> <chr>   
## 1     0 France  
## 2     1 Belgium 
## 3     2 Germany 
## 4     3 Danemark
## 5     4 Croatia 
## 6     5 Slovenia
edges_d3 <- mutate(edges, from = from - 1, to = to - 1);head(edges_d3)
## # A tibble: 6 x 3
##    from    to weight
##   <dbl> <dbl>  <dbl>
## 1     0     2      9
## 2     1     0      4
## 3     0     7      3
## 4     0     8      4
## 5     0     9      2
## 6     0    10      3
p = sankeyNetwork(
  Links = edges_d3, Nodes = nodes_d3, 
  Source = "from", Target = "to", 
  NodeID = "label", Value = "weight",
  fontSize = 16, unit = "Letter(s)")
p
image

2.保存

主要是因为这个桑基图是互动式的。只能导出为html,没有其它选项。如果是forceNetwork出的图,可以在这里手动点保存输出,可桑基图不行。

network3D自带一个saveNetwork函数,只能导出html。

saveNetwork(p,"sankey.html")

这个函数刚好可以对接webshot,把html保存为pdf或者png,干就完事!

这个包需要依赖phantomjs,我搜到的结果是需要自己装,结果发现作者把安装的动作也写成R语言函数了,非常舒适。

library(webshot)
if(!is_phantomjs_installed()){
  install_phantomjs()
}
is_phantomjs_installed()
## [1] TRUE

只要上面是TRUE了,保存就没有问题。

webshot("sankey.html" , "sankey.png")
webshot("sankey.html" , "sankey.pdf")

相关文章

网友评论

    本文标题:听说你的桑基图也无法保存?

    本文链接:https://www.haomeiwen.com/subject/xazxxltx.html