【问题标题】:How to get d3.js tree layout to sort nodes alphabetically?如何让 d3.js 树布局按字母顺序对节点进行排序?
【发布时间】:2016-05-06 05:09:29
【问题描述】:

我正在尝试使用 d3.js 的 this 示例(完整粘贴在下面)来绘制基于 JSON 树结构的树。

这段代码绘制了一棵漂亮的树,但它没有按任何垂直顺序对兄弟节点进行排序。数据恰好已经在underlying JSON object 中排序。

如果基础数据尚未排序,我想知道如何按字母顺序(A 在顶部,Z 在底部,最好不区分大小写)对这些节点进行垂直排序。我需要在下面的代码中更改什么?

开始编辑:

我想在不修改底层 JSON 对象的情况下执行此操作。 我尝试的一件事是在d3.layout.tree() 行之后添加tree.sort(d3.ascending);。但这没有任何效果。我不知道为什么。

结束编辑

<!DOCTYPE html>
    <meta charset="utf-8">
    <style>

    .node {
      cursor: pointer;
    }

    .node circle {
      fill: #fff;
      stroke: steelblue;
      stroke-width: 1.5px;
    }

    .node text {
      font: 10px sans-serif;
    }

    .link {
      fill: none;
      stroke: #ccc;
      stroke-width: 1.5px;
    }

    </style>
    <body>
    <script src="//d3js.org/d3.v3.min.js"></script>
    <script>

    var margin = {top: 20, right: 120, bottom: 20, left: 120},
        width = 960 - margin.right - margin.left,
        height = 800 - margin.top - margin.bottom;

    var i = 0,
        duration = 750,
        root;

    var tree = d3.layout.tree()
        .size([height, width]);

    var diagonal = d3.svg.diagonal()
        .projection(function(d) { return [d.y, d.x]; });

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.right + margin.left)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.json("/mbostock/raw/4063550/flare.json", function(error, flare) {
      if (error) throw error;

      root = flare;
      root.x0 = height / 2;
      root.y0 = 0;

      function collapse(d) {
        if (d.children) {
          d._children = d.children;
          d._children.forEach(collapse);
          d.children = null;
        }
      }

      root.children.forEach(collapse);
      update(root);
    });

    d3.select(self.frameElement).style("height", "800px");

    function update(source) {

      // Compute the new tree layout.
      var nodes = tree.nodes(root).reverse(),
          links = tree.links(nodes);

      // Normalize for fixed-depth.
      nodes.forEach(function(d) { d.y = d.depth * 180; });

      // Update the nodes…
      var node = svg.selectAll("g.node")
          .data(nodes, function(d) { return d.id || (d.id = ++i); });

      // Enter any new nodes at the parent's previous position.
      var nodeEnter = node.enter().append("g")
          .attr("class", "node")
          .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
          .on("click", click);

      nodeEnter.append("circle")
          .attr("r", 1e-6)
          .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

      nodeEnter.append("text")
          .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
          .attr("dy", ".35em")
          .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
          .text(function(d) { return d.name; })
          .style("fill-opacity", 1e-6);

      // Transition nodes to their new position.
      var nodeUpdate = node.transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

      nodeUpdate.select("circle")
          .attr("r", 4.5)
          .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

      nodeUpdate.select("text")
          .style("fill-opacity", 1);

      // Transition exiting nodes to the parent's new position.
      var nodeExit = node.exit().transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
          .remove();

      nodeExit.select("circle")
          .attr("r", 1e-6);

      nodeExit.select("text")
          .style("fill-opacity", 1e-6);

      // Update the links…
      var link = svg.selectAll("path.link")
          .data(links, function(d) { return d.target.id; });

      // Enter any new links at the parent's previous position.
      link.enter().insert("path", "g")
          .attr("class", "link")
          .attr("d", function(d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal({source: o, target: o});
          });

      // Transition links to their new position.
      link.transition()
          .duration(duration)
          .attr("d", diagonal);

      // Transition exiting nodes to the parent's new position.
      link.exit().transition()
          .duration(duration)
          .attr("d", function(d) {
            var o = {x: source.x, y: source.y};
            return diagonal({source: o, target: o});
          })
          .remove();

      // Stash the old positions for transition.
      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });
    }

    // Toggle children on click.
    function click(d) {
      if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
      update(d);
    }

    </script>

【问题讨论】:

    标签: javascript json d3.js


    【解决方案1】:

    而不是这个:

    tree.sort(d3.ascending)
    

    这样做:

    var tree = d3.layout.tree()
        .size([height, width]).sort(function(a,b){
          return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
        });;
    

    工作代码here

    【讨论】:

    • 谢谢!!!如果我不关心不区分大小写,我可以使用d3.ascending 吗?你能告诉我怎么做吗?我找不到任何使用它的例子。
    • 对于对象排序,您需要提供排序功能 d3.ascending 将不起作用。如果您不关心不区分大小写,请执行以下操作:return a.name.localeCompare(b.name);
    • 您好,是否可以更新您对 d3 v4/v5 的答案?我意识到排序功能在 v4 之后发生了变化。这会有很大帮助。谢谢。
    【解决方案2】:

    如果你的flare.json与示例类似,你可以使用js排序函数来处理。

    if (error) throw error;
    
    flare.children.sort(function(a, b){
        if(a.name < b.name) return -1;
        if(a.name > b.name) return 1;
        return 0;
    });
    

    【讨论】:

    • 我不希望修改底层的 JSON 结构。难道没有我可以在树上设置的标志来做到这一点吗?
    • @SaqibAli 根据文档github.com/mbostock/d3/wiki/Tree-Layout,在树中有一个排序函数,它使用升序和降序特征来执行此操作。所以我猜没有你想要的标志。但是,如果您也想保留原始 JSON,为什么不将这个排序后的 JSON 绑定到一个新对象中呢?
    • 查看我对原始问题的编辑,我在其中回答了您的评论。谢谢。
    猜你喜欢
    • 2015-01-13
    • 2012-03-31
    • 2021-08-12
    • 2021-01-19
    • 2021-04-29
    • 1970-01-01
    • 2011-08-29
    • 2010-11-23
    • 1970-01-01
    相关资源
    最近更新 更多