以下代码适用于d3 v3:
// data truncated for brevity
var data.inner = [{
"candidate": "hillary",
"data": [{
"committee.name": "CITIZENS UNITED SUPER PAC LLC",
"candidate": "hillary",
"spent": 2243599
}, {
"committee.name": "FREEDOM'S DEFENSE FUND",
"candidate": "hillary",
"spent": 2481851
}]
}, {
"candidate": "trump",
"data": [{
"committee.name": "CITIZENS UNITED SUPER PAC LLC",
"candidate": "trump",
"spent": 255281
}, {
"committee.name": "CLUB FOR GROWTH ACTION",
"candidate": "trump",
"spent": 14869434
}]
}]
var bubble_inner = d3.layout.pack()
.value(function(d) {
// This returns a sum in integer
// ex. Hillary returns 4725450 = 2243599 + 2481851
return _(d.data).chain()
.pluck("spent")
.reduce(function(memo, num) {
return memo + num;
}, 0)
.value();
})
.sort(null)
.size([2 * radius_pack, 2 * radius_pack])
.padding(padding_pack);
var node_inner_g = inner.selectAll("g.node_inner")
.data(
bubble_inner.nodes({ children: data.inner })
.filter(function(d) {
return !d.children;
})
)
.enter()
.append("g")
// do stuff
我很难理解第4版中的新d3.pack()
和d3.hierarchy()
。我知道我应该在sum()
hierarchy
内放置一些逻辑,但我无法绕过它。
答案 0 :(得分:1)
我这样想:
var bubble_inner = d3.pack()
.size([2 * radius_pack, 2 * radius_pack])
.padding(padding_pack);
var root = d3.hierarchy({"children": data.inner})
.sum(function(d) {
return _(d.data).chain()
.pluck("spent")
.reduce(function(memo, num) {
return memo + num;
}, 0)
.value();
});
var node_inner_g = inner.selectAll("g.node_inner")
.data(
bubble_inner(root).children
)
.enter()
.append("g")
.attr("class", function(d) {
return "node_inner " + d.candidate;
})
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")";
});