问题
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:
- Install PhantomJS. For example using Homebrew for OSX -
brew install phantomjs
- 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