Saving networkD3 Sankey diagram using code only
Asked Answered
G

1

7

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.

Guth answered 8/5, 2017 at 11:51 Comment(1)
Unfortunately this does not appear to be straightforward. The answer to this similar question requires code which uses PhantomJS: #35057233Pittman
P
7

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.

Pittman answered 8/5, 2017 at 12:21 Comment(2)
PhantomJS is now discontinued upstream.Choose
I faced problem in using rbokeh. Here is another nice answer which worked perfectly for me.Biparous

© 2022 - 2024 — McMap. All rights reserved.