问题
I'm trying to make a circle packing chart using d3.js. The problem is that nodes have NaN values in the x and y properties, so all the circles have transform="translate(NaN,NaN)"
Json Data:
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}
]
}]
}]
};
Script:
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+")";});
Could anyone explain why the X and Y node values are NaN? I've created a jsFiddle with the data and the script I wrote: http://jsfiddle.net/nm9Lozn2/2/
回答1:
I think you need to change the argument you pass to .size
of pack
to an array. and also add .value
since your data doesn't have value attributes:
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:
so:
var pack = d3.layout.pack()
.size(500,400);
to:
var pack = d3.layout.pack()
.size([500,400])
.value(function(d) { return d.size; });
回答2:
There's probably several causes for this problem, let me add another possibility, which I just encountered. I was seeing the same issue where d3.layout.pack
was producing NaN
for the coordinates. In my case the issue was that some of the values in my data were negative. Once I made sure they were all zero or greater, it began working fine.
来源:https://stackoverflow.com/questions/30644629/nan-x-and-y-values-in-pack-layout-nodes-using-d3-js