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.

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
tktk234
  • 426
  • 3
  • 12
  • Unfortunately this does not appear to be straightforward. The answer to this similar question requires code which uses PhantomJS: http://stackoverflow.com/questions/35056733/how-to-capture-html-output-as-png-in-r – neilfws May 08 '17 at 12:11

1 Answers1

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.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • PhantomJS is now discontinued upstream. – timothyjgraham Nov 11 '19 at 01:06
  • I faced problem in using `rbokeh`. Here is another [nice answer](https://stackoverflow.com/questions/65158327/how-can-i-save-a-networkd3sankeynetwork-into-a-static-image-automatically-vi#65159713) which worked perfectly for me. – Md. Sabbir Ahmed Jul 06 '21 at 05:50