可折叠Sankey图 - D3

时间:2017-03-09 17:26:28

标签: javascript d3.js sankey-diagram

我想知道如何根据鼠标点击使sankey图折叠/展开节点。

我的图表是:https://bl.ocks.org/TheBiro/f73a2a0625bb803179f3905fe7624e22

例如,我想点击节点" PAGOU"以及要删除的所有后续链接和节点(右侧)。 我是根据Vasco Asturiano(参考readme.md)对话选项制作的。

2 个答案:

答案 0 :(得分:3)

我在上面的回答中修改了以下代码: Collapsible D3 force directed graph with non-tree data

我向节点添加了属性,以跟踪它们是否已折叠以及它们的父节点有多少折叠。此外,它们是否可折叠 - 源节点不应该是可折叠的,因为库似乎不喜欢没有链接的图形。

graph.nodes.forEach(function (d, i) {
  graph.nodes[i] = { "name": d };
  graph.nodes[i].collapsing = 0;    // count of collapsed parent nodes
  graph.nodes[i].collapsed = false;
  graph.nodes[i].collapsible = false;
});

我将链接的代码更改为指向整个源节点或目标节点而不是索引,因为我们需要源节点进行过滤。我还设置了所有目标节点都是可折叠的。

graph.links.forEach(function(e) {
  e.source = graph.nodes.filter(function(n) {
        return n.name === e.source;
      })[0],
  e.target = graph.nodes.filter(function(n) {
        return n.name === e.target;
      })[0];
  e.target.collapsible = true;   
});

我将布局代码拉出到一个函数中,以便我们可以在每次单击节点时调用它。我还添加了代码,每次根据他们和他们的父母是否崩溃来过滤图形节点和链接。

update();

var nodes, links;

function update() {
  nodes = graph.nodes.filter(function(d) {
    // return nodes with no collapsed parent nodes
    return d.collapsing == 0;
  });

  links = graph.links.filter(function(d) {
    // return only links where source and target are visible
    return d.source.collapsing == 0 && d.target.collapsing == 0;
  });

  // Sankey properties
  sankey
    .nodes(nodes)
    .links(links)
    .layout(32);

  // I need to call the function that renders the sakey, remove and call it again, or the gradient coloring doesn't apply (I don't know why)
  sankeyGen();
  svg.selectAll("g").remove();
  sankey.align("left").layout(32);
  sankeyGen();
}

我不得不评论这一行,因为它干扰了点击处理程序,我不确定我在那里做了什么改变。

.on("start", function() {
    //this.parentNode.appendChild(this);
})

我添加了一个点击处理程序来执行折叠。

node.on('click', click);
function click(d) {
  if (d3.event.defaultPrevented) return;
  if (d.collapsible) {
    // If it was visible, it will become collapsed so we should decrement child nodes count
    // If it was collapsed, it will become visible so we should increment child nodes count
    var inc = d.collapsed ? -1 : 1;
    recurse(d);

    function recurse(sourceNode){
      //check if link is from this node, and if so, collapse
      graph.links.forEach(function(l) {
        if (l.source.name === sourceNode.name){
          l.target.collapsing += inc;
          recurse(l.target);
        }
      });
    }
    d.collapsed = !d.collapsed;  // toggle state of node
  }      
  update();
}

cirofdo's Gist

中的完整代码

答案 1 :(得分:0)

上述小提琴适用于标准树木,每个孩子都有一个单亲。但是,对于传统的sankey特别适合的多个父母(格子')场景;这种可折叠的表示可能不那么简单。例如,在展开节点A以显示其子节点时,如果任何A的孩子有其他父母未展开,则父母会自动展开。这可能是你想要的,因为只显示部分亲子关系会产生误导,但无论如何它确实让你感到意外。通过不重新定中节点可以减轻失调。可能存在非预期的组合扩展效应,尤其是对于高度网格化的数据结构。

相关问题