This short but useful tutorial will show how you can automatically make node fill color lighter with each subsequent level of a nodes with each subsequent level in a Force Directed Tree.
The task
By default, ForceDirectedSeries
colors node with a solid color. Its direct descendants, as well as their descendants inherit same color throughout the whole tree.
While it makes it easy to identify relations within separate branches, it also makes it harder to identify the depth or level of each particular node.
This is why we want to make nodes retain same color, but make it a bit lighter with each level of depth.
The solution
The solution is super-easy: we just need to us an adapter to dynamically modify the fill of the node.
An adapter is a custom function that can be attached to an object, which can then modify actual value of any property. (more info about adapters)
Since we need to modify the fill color of the nodes, we'll add an adapter to node template's fill
property:
networkSeries.nodes.template.adapter.add("fill", function(fill, target) { return fill.lighten(target.dataItem.level * 0.25); });
networkSeries.nodes.template.adapter.add("fill", function(fill, target) { return fill.lighten(target.dataItem.level * 0.25); });
{ // ... "series": [{ // ... "nodes": { "adapter": { "fill": function(fill, target) { return fill.lighten(target.dataItem.level * 0.25); }) } } }] }
To explain the above, whenever series needs to apply a fill
to a node, it will now call out custom function, passing in current value of the fill, which is an object of type Color
and the target, which is actual node element.
Our code will access element's data item to determine its level, then use Color
method lighten
to produce a lighter version of the same color and return it.
That's all there is to it.
Example
See the Pen Force-directed tree by amCharts team (@amcharts) on CodePen.