Saving networkD3 Sankey diagram using code only

蹲街弑〆低调 提交于 2021-02-20 13:32:07

问题


I've created a Sankey diagram in R, using the networkD3 package, that I'd like to save as a static image, using code instead of clicking on 'Export' --> 'Save as Image...'.

The current code I've tried (using this Sankey diagram as an example) is:

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()

All I'm getting though is a blank white box when I open the image though.


回答1:


Simplest working solution I've found so far is:

  1. Install PhantomJS. For example using Homebrew for OSX - brew install phantomjs
  2. Install rbokeh - install.packages("rbokeh")

Then:

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")

The result doesn't look great, but this might serve as a starting point for research and improvements.

EDIT: here's another potential solution using the webshot package.



来源:https://stackoverflow.com/questions/43846931/saving-networkd3-sankey-diagram-using-code-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!