d3 Sankey - Highlight all connected paths from start to end

戏子无情 提交于 2019-12-18 15:55:51

问题


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.


回答1:


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 example - http://bl.ocks.org/git-ashish/8959771

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);
}


来源:https://stackoverflow.com/questions/19195888/d3-sankey-highlight-all-connected-paths-from-start-to-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!