d3.tree get min&最大值

时间:2015-12-10 07:29:24

标签: json d3.js

我想获取“size”属性的最小值和最大值(树的json结构包括三个属性:name,size和children) 但我无法获得正确的价值。虽然在json文件中,最大值为100,最小值为5,但我得到的结果是94和100.最奇怪的是,当我将最大大小“100”更改为“99”时,最大值和最小值变为99和11.问题是什么?

这是html文件:

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

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


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

var i = 0, duration = 750, root;

var tree = d3.layout.tree() .size([height, width])  .value(function(d) { return d.size;});

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("./parse_tree.json", function(error, parse_tree) {

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

        update(root);
        });

function update(source1) {
    var originalConsole = console;

    var nodes = tree.nodes(root).reverse(),
        links = tree.links(nodes);

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

    var t_max = d3.max(nodes, function(d) { return d.size;})
        var t_min = d3.min(nodes, function(d) { return d.size;});
    originalConsole.log(t_max);
    originalConsole.log(t_min);
}

</script>

这是json文件:

{
"name":"para",
"size":"11",
"children":[
    {
    "name":"top",
    "size":"32",
    "children":[
        {"name":"S",
         "size":"13",
         "children": [
            {"name":"NP",
            "size":"5",
                "children":[
                {"name":"PRP",
                 "size":"89",
                 "children":[{"name":"You","size":"88"}]
                }
            ]
         },
         {"name":"VP",
          "size":"89",
         "children": [
         {"name":"VBP",
          "size":"15",
         "children":[{"name":"are", "size":"38"}]
         },
         {"name":"NP",
          "size":"83",
         "children": [
         {"name":"DT",
          "size":"29",
         "children":[{"name":"a", "size":"53"}]
         },
         {"name":"NN",
          "size":"50",
         "children":[{"name":"boy", "size":"99"}]
         }
         ]
         }
         ]
         },
         {"name":".",
          "size":"94",
         "children":[{"name":".", "size": "67"}]
        }
        ]
        }
        ]
    }
]
}

1 个答案:

答案 0 :(得分:1)

JSON对象中的size是一个字符串,因此事情变得“不像预期的那样”。

所以,要修复它,你必须将类型更改为int,这在JS中非常直接“幸运”:

var t_max = d3.max(nodes, function(d) {
   return +d.size;
})
var t_min = d3.min(nodes, function(d) {
  return +d.size;
});

...或脚本中的其他位置。

哦,顺便说一句,试试这个:

console.log(d3.extent(nodes, function(d) { return +d.size;})); // [5, 99]