如何在 D3.js 中更改径向树的根

How to change the root of a radial tree in D3.js

本文关键字:D3 js      更新时间:2023-09-26

我在 D3 中的径向树有问题.js

我想将选定的节点(单击时)放在径向树的中心,并让整个树重新适应这个新设置。在我的更新函数中,我可以将根设置为所选节点:

root = source; 

但是,这仅显示所选节点和子节点,但我希望将父节点(及其子节点)放在所选节点的顶部,将所选节点的子节点放在其底部。

我尝试的是将选定的节点从父级的子节点数组中删除。然后将此更改的父节点推送为所选节点的子节点,但这会产生递归错误。

var index = source.parent.children.indexOf(source);
source.parent.children.splice(0, 1);
source.parent.parent = source;
source.children.push(source.parent);

完整代码在这里

我将不胜感激任何帮助或指示。

谢谢

这是一个递归函数,负责重新排列:

function makeRoot(source) {
   if (!source.parent) return; //nothing to do if source is already root
   makeRoot(source.parent); //flip the higher branches recursively so that the parent becomes root of the tree 
   var index = source.parent.children.indexOf(source);
   source.parent.children.splice(index, 1);  //corrected here: you need to remove the right element from the children list
   source.parent.parent = source;
   source.children.push(source.parent);
   delete source.parent; //added: now that the original parent is linked, make source the root of the tree
}

我不知道如何强制原始节点的子节点被吸引到南方,其余的被吸引到北方。首先要做的是知道每个节点必须在哪一侧(这很容易:默认情况下所有节点都是"北",然后在调用makeRoot之前从source访问子树,并告诉它们为"南")。但在那之后,我对 d3 的树布局不够熟悉,无法强制执行"北/南"约束。


更新 对于南北向,您可以尝试以下操作:

  • 保持指针oldParent=source.parent指向所选节点的原始父节点
  • 布局完成后,在更新 SVG 之前,计算offsetX= 90- oldParent.x(父位置和北轴之间的差异 - 注意:我不确定北轴是 90°,但它应该是 0、90、180 或 270 之一..只需尝试它们;)
  • 将所有节点移动offsetX量(保持角度在 0 到 359 之间):

    nodes.forEach(function(d) {
        d.x = (d.x + offsetX) % 360;
    });
    
  • 然后你可以更新 SVG:整个树应该旋转,以便原始父树指向北方......这应该足以获得您想要的视觉效果。


更新 #2 另一种南北对齐的方法。

请参阅此处的小提琴:https://jsfiddle.net/qo4w0ktn/4/

这个想法是计算原始子项中最左边和最右边的叶子的角度,并旋转整个图,直到这两个角度的平均值指向南方。这意味着您需要跟踪树中的"原始"子项,这是通过我的d.real_children属性完成的。函数leftmostLeafrightmostLeaf很简单(参见小提琴)。

  function rotateSouth(source, nodes) {
    var lx = leftmostLeaf(source);
    var rx = rightmostLeaf(source);
    if (lx>rx) rx += 360; //this happens if the interval overlap angle 0
    var offsetX= 180- (lx+rx)/2; //the median point (=(lx+rx)/2) should be pushed south (=180)
    nodes.forEach(function(d) {
      d.x = (d.x + offsetX) % 360; //rotate every node by the same offset
    });  
  }