【问题标题】:Node size proportional to number of children in D3节点大小与 D3 中的子节点数成正比
【发布时间】:2014-11-12 12:34:09
【问题描述】:

我创建了这个点击展开折叠网络 -http://jsfiddle.net/5Lv8gkqv/

var width = 960,
    height = 500,
    root = {
 "name": "Chocolate", "tag":"class",
 "children": [
  {
   "name": "Wafer", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "KitKat", "tag":"product"}
     ]
    }
   ]
  },

  {
   "name": "White", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "Milkybar", "tag":"product"}
     ]
    }
   ]
  },

    {
   "name": "Caramel", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "BarOne", "tag":"product"}
     ]
    }
   ]
  },    
    {
   "name": "Milk", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "Nestle Milk", "tag":"product"}
     ]
    },  {
      "name": "Cadbury", "tag":"company",
     "children": [
      {"name": "Dairy Milk", "tag":"product"}
     ]
    }
   ]
  }




 ]
};

var force = d3.layout.force()
    .linkDistance(150)
    .charge(-120)
    .gravity(.05)
    .size([width, height])
    .on("tick", tick);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

flatten(root); //to set ids
setParents(root, null);
collapseAll(root);
root.children = root._children;
root._children = null;
update();

function update() {
  var nodes = flatten(root),
      links = d3.layout.tree().links(nodes);
  // Restart the force layout.
  force
      .nodes(nodes)
      .links(links)
      .start();

  // Update links.
  link = link.data(links, function(d) { return d.target.id; });

  link.exit().remove();

  link.enter().insert("line", ".node")
      .attr("class", "link");

  // Update nodes.
  node = node.data(nodes, function(d) { return d.id; });

  node.exit().remove();

  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .on("click", click)
      .call(force.drag);

  nodeEnter.append("circle")
      .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });

  nodeEnter.append("text")
      .attr("dy", ".35em")
      .text(function(d) { return d.name; });

  node.select("circle")
      .style("fill", color);
}

function tick() {
  link.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; });

  node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}

function color(d) {
  return d._children ? "#3182bd" // collapsed package
      : d.children ? "#c6dbef" // expanded package
      : "#fd8d3c"; // leaf node
}

// Toggle children on click.
function click(d) {
  if (d3.event.defaultPrevented) return; // ignore drag
  if (d.children) {
      collapseAll(d);
  } else {
      if (d._parent){
          d._parent.children.forEach(function(e){
              if (e != d){
                  collapseAll(e);
              }
          });
      }
    d.children = d._children;
    d._children = null;
  }
  update();
}

function collapseAll(d){
    if (d.children){
        d.children.forEach(collapseAll);
        d._children = d.children;
        d.children = null;
    }
    else if (d._childred){
        d._children.forEach(collapseAll);
    }
}

// Returns a list of all nodes under the root.
function flatten(root) {
  var nodes = [], i = 0;

  function recurse(node) {
    if (node.children) node.children.forEach(recurse);
    if (!node.id) node.id = ++i;
    nodes.push(node);
  }
  recurse(root);
  return nodes;
}

function setParents(d, p){
    d._parent = p;
  if (d.children) {
      d.children.forEach(function(e){ setParents(e,d);});
  } else if (d._children) {
      d._children.forEach(function(e){ setParents(e,d);});
  }
}

现在的问题是,我想知道节点大小是否可能与子节点的数量成正比。所以父节点将是最大的圆,叶子节点将是最小的,而中间节点的大小将取决于每个子节点的数量。

【问题讨论】:

标签: javascript svg d3.js force-layout


【解决方案1】:

您可以使用d3.scale.linear 计算与子节点数量成比例的节点半径。 d3.scale 还有助于找到范围之间的半径。这是更新的fiddle

 var minRadius = 10;
 var maxRadius = 15;
 var scale = d3.scale.linear().range([minRadius,maxRadius]);
 nodeEnter.append("circle")
    .attr("r", function(d) { 
        if(d.children)
            return scale(d.children.length);
        else if(d._children)
            return scale(d._children.length);
        else
            return minRadius;
    });

【讨论】:

    【解决方案2】:

    对于一个完整的解决方案,您实际上需要使用递归函数来首先计算每个节点的total 个子节点(不仅仅是一级子节点)。例如:

    var bubble_up_total_children = function(node) {
      var child, _i, _len, _ref;
      if (node.children && node.children.length > 0) {
        _ref = node.children;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          child = _ref[_i];
          bubble_up_total_children(child);
        }
        node.total_children = node.children.length + node.children.reduce(function(a, b) {
          return a.total_children + b.total_children;
        });
      } else {
        node.total_children = 0;
      }
    };
    
    bubble_up_total_children(root);
    

    从那里您现在可以使用@Gilsha 的答案中已记录的 d3.scale 根据每个节点上的新 total_children 属性计算大小。

    【讨论】:

    【解决方案3】:

    更新:现在考虑到未显示的孩子,使用@Gilsha 回答中的想法。


    当然,您可以将每个&lt;circle&gt; 的半径设置为与他们拥有的孩子的数量成正比:

    node.select("circle")
        .attr("r", function(d){
             var numKids = 0;
             if (d.children) numKids += d.children.length;
             if (d._children) numKids += d._children.length;
             return 10 * (numKids + 1);
    })
    

    r 是某个半径。使用r=10 并在"wafer" 节点上切换,您会得到:

    【讨论】:

    • 这工作正常,但我点击“晶圆”以使其大小与其孩子的数量成正比。默认情况下,巧克力最大,而它的 4 个孩子的大小相同。哪个 shudnt 发生,因为“Milk”有两个孩子,因此“milk”应该是第二大节点大小。希望你明白了
    猜你喜欢
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2018-12-10
    相关资源
    最近更新 更多