christophergandrud / networkD3

D3 JavaScript Network Graphs from R
http://christophergandrud.github.io/networkD3
649 stars 270 forks source link

Return position/order of nodes #286

Closed ajwilk closed 2 years ago

ajwilk commented 2 years ago

Hi there, Thanks for a great package. How can I extract the optimized position or order of the nodes from the sankeyNetwork? It seems that node position is calculated in JS during creation of the widget and isn't returned in a sankeyNetwork object.

My goal is to create an alluvial plot via the ggalluvial package but I can't find any package in R that optimizes the positions of nodes to minimize flow crossings for either alluvial or Sankey networks. So my idea is to have sankeyNetwork do that heavy lifting for me and then pass the node positions ggalluvial to make my alluvial plot.

Thanks!

cjyetman commented 2 years ago

Definitely not directly, but if you add some custom JavaScript, open the htmlwidget output in your browser, and inspect the console in your browser, you could get something like this...

library(networkD3)
library(htmlwidgets)

URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/',
              'master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)

p <- sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source',
              Target = 'target', Value = 'value', NodeID = 'name',
              units = 'TWh', fontSize = 12, nodeWidth = 30)

customJS <- 'function() { console.log(this.sankey.nodes().map(d => [d.name, d.x, d.y])); }'
onRender(p, customJS)
Screen Shot 2021-09-17 at 15 03 39
ajwilk commented 2 years ago

thanks so much @cjyetman! I should be able to work with this.