之前寫(xiě)過(guò)畫(huà)桑基圖和網(wǎng)絡(luò)圖的推文:http://www.reibang.com/p/ff295d3444b4眶痰。今天發(fā)現(xiàn)瘤旨,桑基圖居然沒(méi)辦法直接保存為pdf竖伯,png這些常用的格式存哲。搜索了一下,發(fā)現(xiàn)需要借助外力–webshot包七婴。
1.畫(huà)伤钔担基圖
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
2.保存
主要是因?yàn)檫@個(gè)桑基圖是互動(dòng)式的打厘。只能導(dǎo)出為html修肠,沒(méi)有其它選項(xiàng)。如果是forceNetwork出的圖户盯,可以在這里手動(dòng)點(diǎn)保存輸出嵌施,可伤腔基圖不行。
network3D自帶一個(gè)saveNetwork函數(shù)吗伤,只能導(dǎo)出html吃靠。
saveNetwork(p,"sankey.html")
這個(gè)函數(shù)剛好可以對(duì)接webshot,把html保存為pdf或者png足淆,干就完事巢块!
這個(gè)包需要依賴phantomjs,我搜到的結(jié)果是需要自己裝,結(jié)果發(fā)現(xiàn)作者把安裝的動(dòng)作也寫(xiě)成R語(yǔ)言函數(shù)了缸浦,非常舒適夕冲。
library(webshot)
if(!is_phantomjs_installed()){
install_phantomjs()
}
is_phantomjs_installed()
## [1] TRUE
只要上面是TRUE了,保存就沒(méi)有問(wèn)題裂逐。
webshot("sankey.html" , "sankey.png")
webshot("sankey.html" , "sankey.pdf")