Different colors for each circle - D3 circle pack

4.1k views Asked by At

I have done the bubble chart. But I'm not getting different colors for each bubble. How could I do that? How could I give different colors for each circle? And the circle data with the highest value should always come at the center surrounded by other bubbles.

Snippet:

var diameter = 200,
format = d3.format(",d"),
color = ["#7b6888", "#ccc", "#aaa", "#6b486b"];

 var bubble = d3.layout.pack()
.size([diameter, diameter]);

   var svg = d3.select("#bubbleCharts").append("svg")
.attr("width", diameter + 10)
.attr("height", diameter)
.attr("class", "bubble");

  var a;

   d3.json("flare.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 + 20 + "," + d.y + ")"; });

   node.append("circle")
  .attr("r", function(d) { return d.r+ 7; })
  .style("fill", function(d) { 
  for(a in color){
  return color[a]; };} );

    node.append("text")
  .attr("dy", ".3em")
  .style("text-anchor", "middle")
  .text(function(d) { return d.value+"%"; });
  });

   function classes(root) {
    var classes = [];

    function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
      else classes.push({packageName: name, value: node.value});
   }

     recurse(null, root);
      return {children: classes};
     }

My data is:

   {
     "name": "Spending Activity",
     "children": [
         {"name": "Petrol", "value": 60},
         {"name": "Travel", "value": 10},
         {"name": "Medical", "value": 25},
         {"name": "Shopping", "value": 5}
     ]
   }
2

There are 2 answers

8
Lars Kotthoff On BEST ANSWER

You probably want a colour scale to get the fill colours:

var colour = d3.scale.category20();

Then you can set the fill colour like this:

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

As for the positions of the nodes, the pack layout doesn't provide any functionality to affect that, i.e. you cannot force a particular circle to be in the center.

0
VividD On

This reference card may be handy while choosing built-in D3 color sets:

enter image description here

Alternatively, you can use colorbrewer color sets: (see example here)

enter image description here