使用 d3.js 的 Pack Layout 节点中的 NaN x 和 y 值

NaN x and y values in Pack Layout nodes using d3.js

我正在尝试使用 d3.js 制作圆形包装图。问题是节点在 x 和 y 属性中有 NaN 值,所以所有圆圈都有 transform="translate(NaN,NaN)"

Json数据:

 var data = {
     "name": "flare",
     "children": [
      {
       "name": "analytics",
       "children": [
        {
         "name": "cluster",
         "children": [
          {"name": "AgglomerativeCluster", "size": 3938},
          {"name": "CommunityStructure", "size": 3812},
         ]
        },
        {
         "name": "graph",
         "children": [
          {"name": "BetweennessCentrality", "size": 3534}
         ]
        }]
    }]
    };

脚本:

    var diameter = 200;
    var w = 500;
    var h = 400;

    var pack = d3.layout.pack()
                .size(500,400);

    var svg = d3.selectAll("body").append("svg")
                .attr({width:w,height:h})
                .append("g").attr("transform","translate("+w/2+","+h/2+")");

    var nodes = pack.nodes(data);

    var circles = svg.selectAll("circle")
                    .data(nodes)
                    .enter()
                    .append("circle")
                        .attr("r",function(d){return d})
                        .attr("transform", function(d){return "translate("+d.x+","+d.y+")";});

谁能解释一下为什么 X 和 Y 节点值为 NaN?我用数据和我写的脚本创建了一个 jsFiddle:http://jsfiddle.net/nm9Lozn2/2/

我认为您需要将传递给 pack.size 的参数更改为数组。并添加 .value 因为您的数据没有值属性:

https://github.com/mbostock/d3/wiki/Pack-Layout#value

If value is specified, sets the value accessor to the specified function. If value is not specified, returns the current value accessor, which assumes that the input data is an object with a numeric value attribute:

所以:

var pack = d3.layout.pack()
            .size(500,400);

至:

var pack = d3.layout.pack()
            .size([500,400])
            .value(function(d) { return d.size; });

这个问题可能有多种原因,让我补充一下我刚刚遇到的另一种可能性。我看到了 d3.layout.pack 为坐标生成 NaN 的相同问题。就我而言,问题是我数据中的某些值是负数。一旦我确定它们都是零或更大,它就开始正常工作。