javascriptd3.jscolorscircle-pack

How to display d3 bubbles in different colors for a dataset with one branch and many children?


Developing a d3 bubble chart by following the example posted at http://bl.ocks.org/mbostock/4063269:

enter image description here

My dataset is has one branch but many children (see sample below). All my bubbles are displayed in the same color. Is it possible to modify the logic to generate different color bubbles for each children in the same branch? If so, any assistance would be much appreciated.

{
 "name": "mydata",
 "children": [
  {"name": "test1", "size": 5},
  {"name": "test2", "size": 10},
  {"name": "test3", "size": 15},
  {"name": "test4", "size": 20}
 ]
}

Solution

  • Simply pass a different datum to the color function, e.g. the index:

    node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d, i) { return color(i); });
    

    or, for your data, size:

    node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return color(d.size); });