score:8

So the following approach can give different levels of the layout different "heights". You have to take care that with a radial layout you risk not having enough spread for small circles to fan your text without overlaps, but let's ignore that for now.

The key is to realize that the tree layout simply maps things to an arbitrary space of width and height and that the diagonal projection maps width (x) to angle and height (y) to radius. Moreover the radius is a simple function of the depth of the tree.

So here is a way to reassign the depths based on the text lengths:

First of all, I use the following (jQuery) to compute maximum text sizes for:

``````var computeMaxTextSize = function(data, fontSize, fontName){
var maxH = 0, maxW = 0;

var div = document.createElement('div');
document.body.appendChild(div);
\$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none',
margin:0,
});

\$(div).css("font", fontSize + 'px '+fontName);

data.forEach(function(d) {
\$(div).html(d);
maxH = Math.max(maxH, \$(div).outerHeight());
maxW = Math.max(maxW, \$(div).outerWidth());
});

\$(div).remove();
return {maxH: maxH, maxW: maxW};
}
``````

Now I will recursively build an array with an array of strings per level:

``````var allStrings = [[]];
var childStrings = function(level, n) {
var a = allStrings[level];
a.push(n.name);

if(n.children && n.children.length > 0) {
if(!allStrings[level+1]) {
allStrings[level+1] = [];
}
n.children.forEach(function(d) {
childStrings(level + 1, d);
});
}
};
childStrings(0, root);
``````

And then compute the maximum text length per level.

``````var maxLevelSizes = [];
allStrings.forEach(function(d, i) {
maxLevelSizes.push(computeMaxTextSize(allStrings[i], '10', 'sans-serif'));
});
``````

Then I compute the total text width for all the levels (adding spacing for the little circle icons and some padding to make it look nice). This will be the radius of the final layout. Note that I will use this same padding amount again later on.

``````var padding = 25; // Width of the blue circle plus some spacing

var diameter = totalRadius * 2; // was 960;

var tree = d3.layout.tree()
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
``````

Now we can call the layout as usual. There is one last piece: to figure out the radius for the different levels we will need a cumulative sum of the radii of the previous levels. Once we have that we simply assign the new radii to the computed nodes.

``````// Compute cummulative sums - these will be the ring radii
var newDepths = maxLevelSizes.reduce(function(prev, curr, index) {
return prev;
},);

var nodes = tree.nodes(root);

// Assign new radius based on depth
nodes.forEach(function(d) {
d.y = newDepths[d.depth];
});
``````

Eh voila! This is maybe not the cleanest solution, and perhaps does not address every concern, but it should get you started. Have fun!