Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving networkD3 Sankey diagram using code only

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.

like image 743
cs234 Avatar asked May 08 '17 11:05

cs234


1 Answers

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.

like image 100
neilfws Avatar answered Oct 16 '22 07:10

neilfws