D3强制布局,在树中移动分支而不是节点

时间:2016-10-08 22:50:03

标签: javascript d3.js

我有一棵树和叶子之间的其他链接。我想为这些节点应用强制布局,以便分支被迫靠近在一起。不是单独的节点(应该保留树布局)。

因此,对于下面的图像,我想要从7和4开始的分支来更改位置,以便节点5和0变得更近。到目前为止,我只是将单独的节点移动到一起。请参见下面的其他图片

以下是jsfiddle link您能否建议使用强制布局更改分支位置的最佳方法?

enter image description here

enter image description here

我仅在某些节点上应用了力布局:

// assign special type on creation/////////////////////////////////////
var ind1 = 0;
var ind2 = 5;
nodes.forEach(function(d, i) {
  if (i ==  ind1 || i == ind2) {
    d.dataType = 'special';
  } else {
    d.dataType = 'none';
  }
}
)
// draw path between special nodes/////////////////////////////////////
var nodeS = nodes[ind1];
    var nodeT = nodes[ind2];
    var newLink = {source: nodeS, target: nodeT};
    specialLinks.push(newLink);
    nodesSelected.push(nodeS);
    nodesSelected.push(nodeT);

    linkSel = svg.selectAll('path.linkExtra').data(specialLinks);
    nodeSel = svg.selectAll('g.node').filter(function(d,i){
      return d3.select(this).attr('data-type') == 'special';
    })

    linkSel.enter().append('path')
        .attr('class', 'linkExtra')
        .attr('d', d3.svg.diagonal().projection(function(d) {
          return [d.y, d.x];
        }));

// create force layout/////////////////////////////////////
var force = d3.layout.force()
  .gravity(0)
  .charge(20)
  .linkDistance(100)
  .linkStrength(1)
  .size([500, 500]);



 // main function to apply forces/////////////////////////////////////
     function inittForce() { 
    force
        .nodes(nodesSelected)
        .links(specialLinks)
         .start();


    force.on('tick', function(e) {

      linkSel.attr('x1', function(d) { return d.source.x; })
          .attr('y1', function(d) { return d.source.y; })
          .attr('x2', function(d) { return d.target.x; })
          .attr('y2', function(d) { return d.target.y; });

      nodeSel.attr('cx', function(d, i) {return  d.x;})
          .attr('cy', function(d) { return d.y; });

      svg.selectAll('*').remove();
      drawTree();
      drawPath();
    });
  }

1 个答案:

答案 0 :(得分:0)

我不认为强制布局与层次结构布局一起在这里起作用。

我希望以编程方式预先处理数据,以便发送到分层布局的数据根据​​其连接性进行排序。对于您的示例,我已交换了几个treeData数组元素以获得效果。

http://jsfiddle.net/1ahutwvp/39/