Published
Edited
Aug 15, 2021
5 stars
Insert cell
Insert cell
Insert cell
Insert cell
{
var width = 960,
height = 500;

// append the svg object to the body of the page
const svg = d3.select(createSvg`<svg width=500 height=500></svg>`);
const g = svg
.attr("width", width)
.attr("height", height)
.append("g")
.attr('transform', `translate(100,${height / 2})`);

const duration = 750;
let i = 0,
root = d3.hierarchy(treeData, function(d) {
return d.children;
});

// Collapse after second level
root.children.forEach(collapse);
root.x0 = 0;
root.y0 = 0;

// Reverse size parameters, in order to maintain order in horizontal layout
loopOverHierarchy(treeData, d => {
if (Array.isArray(d.size)) {
if (!d._size) d._size = d.size.slice();
d.size = d._size.slice().reverse();
}
});

const flexLayout = flextree.flextree();

update(root);

// Collapse the node and all it's children
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}

function loopOverHierarchy(d, callback) {
callback(d);
if (d.children) d.children.forEach(c => loopOverHierarchy(c, callback));
if (d._children) d._children.forEach(c => loopOverHierarchy(c, callback));
}

function update(source) {
// Assigns the x and y position to the nodes
var treeData = flexLayout(root);

// Switch x and y coordinates for horizontal layout
treeData.each(d => {
const x = d.x;
d.x = d.y;
d.y = x;
});

// Compute the new tree layout.
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);

// ****************** Nodes section ***************************

// Update the nodes...
var node = g.selectAll('g.node').data(nodes, d => d.id || (d.id = ++i));

// Enter any new modes at the parent's previous position.
var nodeEnter = node
.enter()
.append('g')
.attr('class', 'node')
.attr("transform", function(d) {
return "translate(" + source.x0 + "," + source.y0 + ")";
})
.on('click', click);

// Add Circle for the nodes
nodeEnter
.append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
});

// Add labels for the nodes
nodeEnter
.append('text')
.attr('pointer-events', 'none')
.attr('dy', '0.35em')
.text(function(d) {
return d.data.name;
})
.attr('text-anchor', 'middle');

// UPDATE
var nodeUpdate = nodeEnter
.merge(node)
.attr("fill", "#fff")
.attr("stroke", "steelblue")
.attr("stroke-width", "3px;")
.style('font', '12px sans-serif');

// Transition to the proper position for the node
nodeUpdate
.transition()
.duration(duration)
.attr("transform", function(event, i, arr) {
const d = d3.select(this).datum();
return "translate(" + d.x + "," + d.y + ")";
});

// Update the node attributes and style
nodeUpdate
.select('circle.node')
.attr('r', 20)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
})
.attr('cursor', 'pointer');

// Remove any exiting nodes
var nodeExit = node
.exit()
.transition()
.duration(duration)
.attr("transform", function(event, i, arr) {
const d = d3.select(this).datum();
return "translate(" + source.x + "," + source.y + ")";
})
.remove();

// On exit reduce the node circles size to 0
nodeExit.select('circle').attr('r', 1e-6);

// On exit reduce the opacity of text labels
nodeExit.select('text').style('fill-opacity', 1e-6);

// ****************** links section ***************************

// Update the links...
var link = g.selectAll('path.link').data(links, function(d) {
return d.id;
});

// Enter any new links at the parent's previous position.
var linkEnter = link
.enter()
.insert('path', "g")
.attr("class", "link")
.attr('d', function(d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal(o, o);
});

// UPDATE
var linkUpdate = linkEnter
.merge(link)
.attr("fill", "none")
.attr("stroke", "#ccc")
.attr("stroke-width", "2px");

// Transition back to the parent element position
linkUpdate
.transition()
.duration(duration)
.attr('d', function(d) {
return diagonal(d, d.parent);
});

// Remove any exiting links
var linkExit = link
.exit()
.transition()
.duration(duration)
.attr('d', function(event, i, arr) {
const d = d3.select(this).datum();
var o = {
x: source.x,
y: source.y
};
return diagonal(o, o);
})
.remove();

// Store the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});

// Creates a curved (diagonal) path from parent to the child nodes
function diagonal(s, t) {
// Define source and target x,y coordinates
const x = s.x;
const y = s.y;
const ex = t.x;
const ey = t.y;

// Values in case of top reversed and left reversed diagonals
let xrvs = ex - x < 0 ? -1 : 1;
let yrvs = ey - y < 0 ? -1 : 1;

// Define preferred curve radius
let rdef = 35;

// Reduce curve radius, if source-target x space is smaller
let r = Math.abs(ex - x) / 2 < rdef ? Math.abs(ex - x) / 2 : rdef;

// Further reduce curve radius, is y space is more small
r = Math.abs(ey - y) / 2 < r ? Math.abs(ey - y) / 2 : r;

// Defin width and height of link, excluding radius
let h = Math.abs(ey - y) / 2 - r;
let w = Math.abs(ex - x) / 2 - r;

// Build and return custom arc command
return `
M ${x} ${y}
L ${x + w * xrvs} ${y}
C ${x + w * xrvs + r * xrvs} ${y}
${x + w * xrvs + r * xrvs} ${y}
${x + w * xrvs + r * xrvs} ${y + r * yrvs}
L ${x + w * xrvs + r * xrvs} ${ey - r * yrvs}
C ${x + w * xrvs + r * xrvs} ${ey}
${x + w * xrvs + r * xrvs} ${ey}
${ex - w * xrvs} ${ey}
L ${ex} ${ey}
`;
}

// Toggle children on click.
function click(event, d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
}

yield svg.node();
}
Insert cell
treeData = ({
name: "A",
size: [100, 100],
children: [
{
name: "BA",
size: [75, 100],
children: [
{ name: "BAA", size: [100, 100] },
{
name: "BAB",
size: [100, 100],
children: [
{ name: "BABA", size: [100, 50] },
{ name: "BABB", size: [100, 50] }
]
},
{ name: "BAC", size: [200, 100] }
]
},
{
name: "BB",
size: [140, 55],
children: [
{ name: "BBA", size: [50, 50] },
{ name: "BBB", size: [50, 50] }
]
}
]
})
Insert cell
Insert cell
d3 = require('d3@v6')
Insert cell
flextree = require("d3-flextree@v2")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more