仅使用代码保存 networkD3 Sankey 图

Saving networkD3 Sankey diagram using code only

我使用 networkD3 包在 R 中创建了一个 Sankey 图,我想将其保存为静态图像,使用代码而不是单击 'Export' --> 'Save as Image...'.

我试过的当前代码(以this桑基图为例)是:

library(networkD3)

URL <- paste0(
  "https://cdn.rawgit.com/christophergandrud/networkD3/",
  "master/JSONdata/energy.json")
Energy <- jsonlite::fromJSON(URL)
# Plot
jpeg( filename = "Sankey.jpg", width = 4000, height = 4000)
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 12, nodeWidth = 30)
dev.off()

虽然我打开图像时得到的只是一个空白的白框。

到目前为止我发现的最简单的工作解决方案是:

  1. 安装PhantomJS。例如,将 Homebrew 用于 OSX - brew install phantomjs
  2. 安装 rbokeh - install.packages("rbokeh")

然后:

library(rbokeh)
sn <- sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
          Target = "target", Value = "value", NodeID = "name",
          units = "TWh", fontSize = 12, nodeWidth = 30)
widget2png(sn, "sankey.png")

结果看起来不太好,但这可以作为研究和改进的起点。

编辑:here's another potential solution 使用 webshot 包。