Public
Edited
Apr 21, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const width = 1100;
const height = width;
const cx = width * 0.52; // adjust as needed to fit
const cy = height * 0.52; // adjust as needed to fit
const radius = Math.min(width, height) / 2 - 100;
const k = 6; // 2^k colors segments per curve
const scale = 1.1;
const initialStep = 70;
//const stepRadius = 0.5;
const roundRadius = 6;
const pi = Math.PI;

const root = treeTidy;

// Adding Arcs
const nodes = root.descendants();
let j = 0;
let links = [];
nodes.forEach((node) => {
if (node.outgoing && j % reduce == 0) {
// exculde index page for the moment?
node.outgoing.forEach((link) =>
links.push({
source: link[0],
target: link[1]
})
);
}
j++;
});
console.log("Links are: ");
console.log(links);
console.log("root is: ");
console.log(links);
console.log("links root are: ");
console.log(root.links());
console.log("root desc are: ");
console.log(root.descendants());

// ------------------ Chart ------------------ //

// initionalisation
const orbites = [[]]; // already has a first empty orbite

// function that calculate the param for the arcs used in Arc links
const arcLinks = (link, lower = false) => {
const a0 = link.source.x;
const r0 = link.source.y;
const a1 = link.target.x;
const r1 = link.target.y;

let diff = a1 - a0;
if (diff < 0) {
diff += 2 * Math.PI;
}
if (diff > Math.PI) {
diff -= 2 * Math.PI;
}
let startAngle = a0;
let endAngle = a0 + diff;

// orbites
const nodeOrbite = [];

// populate the nodeOrbite with ranges between 0 and 2pi
if (endAngle < 0) {
nodeOrbite.push([0, startAngle]);
nodeOrbite.push([2 * pi + endAngle, 2 * pi]);
} else if (endAngle > 2 * pi) {
nodeOrbite.push([startAngle, 2 * pi]);
nodeOrbite.push([0, endAngle - 2 * pi]);
} else {
nodeOrbite.push([
Math.min(startAngle, endAngle),
Math.max(startAngle, endAngle)
]);
}

let o = 0; // start at orbite 1
let fitted = false;

for (const num in orbites) {
if (doesItfitIn(nodeOrbite, orbites[num])) {
orbites[num] = orbites[num].concat(nodeOrbite);
fitted = true;
break;
}
o++;
}

if (!fitted) orbites.push(nodeOrbite); // add our array on a new orbite
if (r0 == r1) {
// d.height == 0
const orbiteAltitude = initialStep + stepRadius * o;

return d3
.arc()
.startAngle(startAngle)
.endAngle(endAngle)
.innerRadius(r0)
.outerRadius(lower ? r0 + 10 : r0 + orbiteAltitude)
.cornerRadius(roundRadius)(link);
}
};

// ------------- SVG ----------- //

// Creates the SVG container.
const svg = d3
.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-cx * scale, -cy * scale, width * scale, height * scale])
.attr("style", "width: 100%; height: auto; font: 10px sans-serif;");

// Append Arc links
svg
.append("g")
.attr("fill", "none")
.attr("stroke", "#777")
.attr("stroke-opacity", 0.8)
.attr("stroke-width", 0.5)
.selectAll()
.data(links)
.join("path")
.attr("d", (d) => arcLinks(d))
.attr(
"class",
(d, i) =>
"linkId-" + d.source.data.name + " " + "linkId-" + d.target.data.name
);

// hidding the bottom edge of the arcs
svg // could use clone(), but it messes when highlight
.append("g")
.attr("fill", "none")
.attr("stroke", "white")
.attr("stroke-opacity", 1)
.attr("stroke-width", 5)
.selectAll()
.data(links)
.join("path")
.attr("d", (d) => arcLinks(d, true));

// Append Radial links.
svg
.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll()
.data(root.links())
.join("path")
.attr(
"d",
d3
.linkRadial()
.angle((d) => d.x)
.radius((d) => d.y)
)
.attr(
"class",
(d, i) => "radialLinkId-" + d.source.name + "-" + d.target.name
);

// Append nodes.
svg
.append("g")
.selectAll()
.data(root.descendants())
.join("circle")
.attr(
"transform",
(d) => `rotate(${(d.x * 180) / Math.PI - 90}) translate(${d.y},0)`
)
.attr("fill", (d) => (d.children ? "#555" : "#999"))
.attr("r", 2.5)
.attr("name", (d) => "circle-" + d.data.name)
.attr("class", (d, i) => {
const linksToNode = links.filter((node) => node.target.name == d.name);
const linksFromNode = links.filter((node) => node.source.name == d.name);
let string = "";
for (const link of linksToNode) {
string += "circle-" + link.source.name + " ";
}
for (const link of linksFromNode) {
// this seems not to work...
string += "circle-" + link.target.name + " ";
}
return string;
});

// Append labels.
svg
.append("g")
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.selectAll()
.data(root.descendants())
.join("text")
.attr(
"transform",
(d) =>
`rotate(${(d.x * 180) / Math.PI - 90}) translate(${d.y},0) rotate(${
d.x >= Math.PI ? 180 : 0
})`
)
.attr("dy", "0.31em")
.attr("x", (d) => (d.x < Math.PI === !d.children ? 6 : -6))
.attr("text-anchor", (d) =>
d.x < Math.PI === !d.children ? "start" : "end"
)
.attr("paint-order", "stroke")
.attr("stroke", "white")
.attr("fill", "currentColor")
.text((d) => d.data.name)
.attr("name", (d) => d.data.name)
.attr("class", (d, i) => {
const linksToNode = links.filter(
(node) => node.target.data.name == d.data.name
);
const linksFromNode = links.filter(
(node) =>
node.source.data.name == d.data.name &&
node.source.data.name != "index"
);
let string = "";
for (const link of linksToNode) {
string += "nodeId-" + link.source.data.name + " ";
}
for (const link of linksFromNode) {
string += "nodeId-" + link.target.data.name + " ";
}
return string;
})
.on("mouseover", function (d, i) {
const name = this.getAttribute("name");
const node = root.descendants().find((d) => d.data.name === name);
const ancestors = node.ancestors();
d3.select(this).attr("font-weight", "bold").attr("fill", "red");
d3.select("#circle-" + name).attr("fill", "red");
d3.selectAll(".circle-" + name).attr("fill", "red");
d3.selectAll(".nodeId-" + name)
.attr("font-weight", "bold")
.attr("fill", "red");
d3.selectAll(".linkId-" + name)
.attr("stroke", "red")
.attr("stroke-opacity", 1)
.attr("stroke-width", 1); // Would be nice to raise()
// https://observablehq.com/@d3/d3-hierarchy
// optimisation https://github.com/d3/d3-hierarchy/issues/58
for (let i = 0; i < ancestors.length - 1; i++) {
console.log(i, ancestors[i], ancestors[i].data.name);
d3.select(
".radialLinkId-" +
ancestors[i + 1].data.name +
"-" +
ancestors[i].data.name
)
.attr("stroke", "red")
.attr("stroke-opacity", 1)
.attr("stroke-width", 1);
d3.select("#" + ancestors[i + 1].data.name)
.attr("font-weight", "bold")
.attr("fill", "red");
d3.select("#circle-" + ancestors[i + 1].data.name).attr("fill", "red");
}
})
.on("mouseout", function (d, i) {
const name = this.getAttribute("name");
const node = root.descendants().find((d) => d.data.name === name);
const ancestors = node.ancestors();
d3.select(this)
.attr("font-weight", "normal")
.attr("fill", "currentColor");
d3.select("#circle-" + name).attr(
"fill",
node.children ? "#555" : "#999"
);
d3.selectAll(".circle-" + name).attr("fill", "#999");
d3.selectAll(".nodeId-" + name)
.attr("font-weight", "normal")
.attr("fill", "currentColor");
d3.selectAll(".linkId-" + name)
.attr("stroke", "#777")
.attr("stroke-opacity", 0.9)
.attr("stroke-width", 0.5);
for (let i = 0; i < ancestors.length; i++) {
console.log(i, ancestors[i], ancestors[i].data.name);
d3.select(
".radialLinkId-" +
ancestors[i + 1].data.name +
"-" +
ancestors[i].data.name
)
.attr("stroke", "#777")
//.attr("stroke-opacity", 0.4)
.attr("stroke-width", 0.5);
d3.select("#" + ancestors[i + 1].data.name)
.attr("font-weight", "normal")
.attr("fill", "currentColor");
d3.select("#circle-" + ancestors[i + 1].data.name).attr(
"fill",
ancestors[i + 1].children ? "#555" : "#999"
);
}
});

if (bundling) {
const line = d3
.lineRadial()
.curve(d3.curveBundle)
.radius((d) => d.y)
.angle((d) => d.x);

const path = ([source, target]) => {
const p = new Path();
line.context(p)(source.path(target));
return p;
};

svg
.append("g")
.attr("fill", "none")
.selectAll()
.data(
d3.transpose(
root
.leaves()
.flatMap((leaf) => leaf.outgoing.map(path))
.map((path) => Array.from(path.split(k)))
)
)
.join("path")
.style("mix-blend-mode", "darken")
//.attr("stroke", (d, i) => color(d3.easeQuad(i / ((1 << k) - 1))))
.attr("stroke", "#555")
.attr("stroke-opacity", 0.1)
.attr("d", (d) => d.join(""));
}
console.log(root);
return svg.node();
}
Insert cell
doesItfitIn = (orbite_A, orbite_B) => {
// Does A fit in B ?
const holeOrbite_B = calculateHoles(orbite_B);

// every ranges has to fit into a hole
let itFits = true;

for (const range_A of orbite_A) {
const a = range_A[0];
const b = range_A[1];
// if we cannot find a range_Hole where it can fit // the set don't overlap !
if (!holeOrbite_B.find((range_H) => range_H[0] < a && b < range_H[1]))
itFits = false;
}
return itFits;
}
Insert cell
calculateHoles = (R) => {
// created by phind with the prompt :
// in javascript, let's say you have an array R of ranges. Ranges are represented by arrays of two number [x,y], where x < y. This give you an array R of arrays. All the number are bounded between 0 and 2pi.
// How do you calculate the "holes" in the array R, i.e. the complementary set of ranges that fill up the space in between the first set of ranges

R.sort((a, b) => a[0] - b[0]);

const holes = [];
let previous_end = 0;

for (const [start, end] of R) {
if (start > previous_end) {
holes.push([previous_end, start]);
}
previous_end = Math.max(previous_end, end);
}

if (previous_end < 2 * Math.PI) {
holes.push([previous_end, 2 * Math.PI]);
}

return holes;
}
Insert cell
data = hierarchy(await FileAttachment("flare.json").json())
Insert cell
function hierarchy(data, delimiter = ".") {
let root;
const map = new Map;
data.forEach(function find(data) {
const {name} = data;
if (map.has(name)) return map.get(name);
const i = name.lastIndexOf(delimiter);
map.set(name, data);
if (i >= 0) {
find({name: name.substring(0, i), children: []}).children.push(data);
data.name = name.substring(i + 1);
} else {
root = data;
}
return data;
});
return root;
}
Insert cell
Insert cell
function id(node) {
return `${node.parent ? id(node.parent) + "." : ""}${node.data.name}`;
}
Insert cell
class Path {
constructor(_) {
this._ = _;
this._m = undefined;
}
moveTo(x, y) {
this._ = [];
this._m = [x, y];
}
lineTo(x, y) {
this._.push(new Line(this._m, this._m = [x, y]));
}
bezierCurveTo(ax, ay, bx, by, x, y) {
this._.push(new BezierCurve(this._m, [ax, ay], [bx, by], this._m = [x, y]));
}
*split(k = 0) {
const n = this._.length;
const i = Math.floor(n / 2);
const j = Math.ceil(n / 2);
const a = new Path(this._.slice(0, i));
const b = new Path(this._.slice(j));
if (i !== j) {
const [ab, ba] = this._[i].split();
a._.push(ab);
b._.unshift(ba);
}
if (k > 1) {
yield* a.split(k - 1);
yield* b.split(k - 1);
} else {
yield a;
yield b;
}
}
toString() {
return this._.join("");
}
}
Insert cell
class Line {
constructor(a, b) {
this.a = a;
this.b = b;
}
split() {
const {a, b} = this;
const m = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
return [new Line(a, m), new Line(m, b)];
}
toString() {
return `M${this.a}L${this.b}`;
}
}
Insert cell
BezierCurve = {
const l1 = [4 / 8, 4 / 8, 0 / 8, 0 / 8];
const l2 = [2 / 8, 4 / 8, 2 / 8, 0 / 8];
const l3 = [1 / 8, 3 / 8, 3 / 8, 1 / 8];
const r1 = [0 / 8, 2 / 8, 4 / 8, 2 / 8];
const r2 = [0 / 8, 0 / 8, 4 / 8, 4 / 8];

function dot([ka, kb, kc, kd], {a, b, c, d}) {
return [
ka * a[0] + kb * b[0] + kc * c[0] + kd * d[0],
ka * a[1] + kb * b[1] + kc * c[1] + kd * d[1]
];
}

return class BezierCurve {
constructor(a, b, c, d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
split() {
const m = dot(l3, this);
return [
new BezierCurve(this.a, dot(l1, this), dot(l2, this), m),
new BezierCurve(m, dot(r1, this), dot(r2, this), this.d)
];
}
toString() {
return `M${this.a}C${this.b},${this.c},${this.d}`;
}
};
}
Insert cell
color = t => d3.interpolateRdBu(1 - t)
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