Skip to content Skip to sidebar Skip to footer

D3 Circle Pack: Setting Circle Colors

I try to use http://mbostock.github.com/d3/ex/bubble.html but with changed colors. I would like to find out how the colors are set in d3.layout.pack.

Solution 1:

In the example you mentioned, the circle color is defined here:

.style("fill", function(d) { returnfill(d.packageName); });

Here, d is the data, bound to the circle. Instead of color, in this example the function passes an object (packageName attribute of d). Each object gets own unique color assigned to it, according to selected color scale:

fill = d3.scale.category20c();

If you are happy with used criteria for coloring (packageName) and all you need is to change colors, you could change the palette (color scale): https://github.com/mbostock/d3/wiki/Ordinal-Scales if you want to change the coloring criteria, then you need to change the return part, replacing it with color value as a function of data d.

Here you can find D3 color constructors: https://github.com/mbostock/d3/wiki/Colors

Solution 2:

You can change the json file for your data and tweak the d3 code to specify which color to fill the each individual bubbles with.

Below is my data, and you can see that I am specifying what color to fill the bubbles with.

{"name":"sentiment","children":[{"name":"positive","children":[{"name":"iphone","size":2000,"color":"green"}]}]}

Then, I add the color attribute that I specified into the node object so that it can be later accessed in d3 function.

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

Then find the function responsible for coloring the bubbles and edit the fill function.

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

My code is edited from the code given at, http://bl.ocks.org/mbostock/4063269

Post a Comment for "D3 Circle Pack: Setting Circle Colors"