Indeed, the color function has to be changed.
This SO Question shows how to assign a unique color to records based on one of their attributes. Read also: d3.js ordinal scales reference.
My understanding is that you want all the nodes to be colored based on their parents. Here is how to do it.
Adapting the data source
For each node, you want to know which parent it has. This will allow you to give a color to each node, based on its parent.
For example, data could look like this (excerpt):
{
"name": "optimization",
"parentName": "analytics",
"children": [
{"name": "AspectRatioBanker", "parentName": "optimization", "size": 7074}
]
}
For each node, parentName
tells you how the group of the record.
This information is missing in the gist you linked, you could process it by traversing the tree and attaching the parentName
information on the fly.
Color scale
An easy way to get colors that can be assigned to groups is to use the categorical color scales built-in d3.js, for example category10.
var nodeColor = d3.scale.category10();
Assigning color to each record
The color
function should be modified in order to assign a color based on the node's parentName
property:
function color(d) {
return nodeColor(d.parentName)
}
You will note that I have modified the function to dynamically assign a color not only to the leaves, but also to the nodes at all levels. This is not compulsory, but I did so to avoid collision between category10
colors, and the hard-coded colors of the gist, which may have looked confusing.
Here is a working demo (fork of the original gist).
Alernatives / variants
You may adapt the code above to assign colors chosen by you for each specific group, using ordinal scale instead of category10
.
var nodeColor = d3.scale.ordinal()
.domain(['none', 'flare', 'analytics', 'graph', 'cluster', 'optimization'])
.range(['black', '#ffaa00', 'grey', 'red', 'green', 'blue'])
This is illustrated here.