Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 Sankey - Highlight all connected paths from start to end

I'm trying to highlight all the connected links and links of their target nodes till the end of the layout.

The first level of highlighting can be easily achieved as follows -

On node click, call highlight_paths(1);

function highlight_paths(stroke_opacity) {
    return function(d,i){
        d.sourceLinks.forEach(function(srcLnk){
            d3.select("#link"+srcLnk.id).style("stroke-opacity", stroke_opacity);
        });
        d.targetLinks.forEach(function(srcLnk){
            d3.select("#link"+srcLnk.id).style("stroke-opacity", stroke_opacity);
        });
    }
}

But I'm not yet able to write correctly a recursive algorithm to get all the sourceLinks and targetLinks of each of the connected source & target nodes.

All thoughts are appreciated!

Thanks.

like image 232
Ashish Singh Avatar asked Oct 05 '13 08:10

Ashish Singh


1 Answers

I was going through the sankey layout code and found a Breadth First Search implementation for traversing the layout nodes. Some knowledge on BFS here - http://www.cse.ohio-state.edu/~gurari/course/cis680/cis680Ch14.html

Purely based on that, here is the function to highlight all the paths from the clicked node in both the directions - Forward ( Target ) and Backward (Source)

Hope this helps someone!

Working examples -

http://bl.ocks.org/git-ashish/8959771

https://observablehq.com/@git-ashish/sankey-diagram

function highlight_node_links(node,i){

  var remainingNodes=[],
      nextNodes=[];

  var stroke_opacity = 0;
  if( d3.select(this).attr("data-clicked") == "1" ){
    d3.select(this).attr("data-clicked","0");
    stroke_opacity = 0.2;
  }else{
    d3.select(this).attr("data-clicked","1");
    stroke_opacity = 0.5;
  }

  var traverse = [{
                    linkType : "sourceLinks",
                    nodeType : "target"
                  },{
                    linkType : "targetLinks",
                    nodeType : "source"
                  }];

  traverse.forEach(function(step){
    node[step.linkType].forEach(function(link) {
      remainingNodes.push(link[step.nodeType]);
      highlight_link(link.id, stroke_opacity);
    });

    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node[step.linkType].forEach(function(link) {
          nextNodes.push(link[step.nodeType]);
          highlight_link(link.id, stroke_opacity);
        });
      });
      remainingNodes = nextNodes;
    }
  });
}

function highlight_link(id,opacity){
    d3.select("#link-"+id).style("stroke-opacity", opacity);
}
like image 125
Ashish Singh Avatar answered Oct 21 '22 01:10

Ashish Singh