I am trying to understand D3 and use it to make a word cloud... Here is the code that uses D3 circle pack for that purpose:
var diameter = 560,
format = d3.format(",d"),
color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort()
.size([diameter, diameter])
.padding(.5);
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
d3.json("data/bubble.json", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("title")
.text(function(d) { return d.className + ": " + format(d.value); });
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return color(d.packageName); });
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d) { return d.className.substring(0, d.r / 3); });
});
The bubbles are coming in random order but I want them to come in sorted order like the biggest circle on left most size then smaller to its right the the smallest one on the right most side ...
How to do that?
In this portion of the code:
var bubble = d3.layout.pack()
.sort()// <-- here
.size([diameter, diameter])
.padding(.5);
Try adding a comparator function in order to tell pack() how you want your data sorted. Otherwise, you'll get the default comparator:
function comparator(a, b) {
return a.value - b.value;
}
For instance, if you wanted to sort based on word length:
function(a, b){
return a.text.length - b.text.length;
}
Here's some more documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With