D3 circle pack: customize circle colors

I am trying to use http://mbostock.github.com/d3/ex/bubble.html but with the colors changed.

I would like to know how the colors are set in d3.layout.pack.

+4
source share
2 answers

In the above example, the color of the circle is defined here:

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

Here d is the data attached to the circle.
Instead of color in this example, the function passes an object (packageName d attribute).
Each object receives its own unique color assigned to it, in accordance with the selected color scale:

 fill = d3.scale.category20c(); 

If you are satisfied with the coloring criteria used (packageName) and all you need to do is change the colors, you can change the palette (color scale):
https://github.com/mbostock/d3/wiki/Ordinal-Scales

if you want to change the coloring criteria, you need to change the returned part, replacing it with a color value as a function of data d .

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

+8
source

You can change the json file for your data and customize the d3 code to indicate what color each individual bubble fills.

Below is my data, and you can see that I indicate what color fill the bubbles.

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

Then I add the color attribute that I pointed to the node object so that it can later be retrieved in the 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 dr; }) .style("fill", function(d) { return d.color; }); 

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

+1
source

All Articles