Public
Edited
Nov 14, 2023
Paused
Fork of Simple D3
1 star
Insert cell
Insert cell
chart = {
const width = 550; // uncomment for responsive width
const height = width;
const radius = Math.min(width, height) / 2 - 80;
const scale = 0.6;
const initialStep = 60;
const stepRadius = 6;
const roundRadius = 6;
const pi = Math.PI;

// ------------------ Data ------------------ //
let dataRadial = [];

for (const key in data) {
let crumb = key.split("/"),
crumbL = crumb.length,
parent = crumb[crumbL - 2],
name = crumb[crumbL - 1];
if (name == "index" && crumbL > 1)
(name = parent), (parent = crumb[crumbL - 3]);

if (parent != "tags")
dataRadial.push({
id: name,
parentId:
parent == undefined ? (name == "index" ? "" : "index") : parent,
...data[key]
});
}
const dataStartified = d3.stratify()(dataRadial); // become a hierarchy usable in D3

// Create a radial cluster layout. The layout’s first dimension (x)
// is the angle, while the second (y) is the radius.
const tree = d3
.cluster()
.size([2 * Math.PI, radius])
.separation((a, b) => (a.parent == b.parent ? 1 : 2) / a.depth);

// Sort the tree and apply the layout.
const root = tree(dataStartified);

root.x = Math.PI / 2;

console.log("root is: ");
console.log(root);

// Data for relationship

const nodes = root.descendants();

let links = [];
nodes.forEach((node) => {
if (node.data.links) {
// exculde index page for the moment?
node.data.links.forEach((link) => {
if (nodes.find((n) => n.data.id == link)) {
const target = nodes.find((n) => n.data.id == link);
if (
// this make sure we dont have duplicates
!links.find((link) => link.target == node && link.source == target)
)
links.push({
source: node,
target: target
});
}
});
}
});

// ------------------ 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 ----------- //
const svg = d3
.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [
-width / 2 / scale,
-height / 2 / 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", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll()
.data(links)
.join("path")
.attr("d", (d) => arcLinks(d))
.attr(
"class",
(d, i) =>
"linkId-" + d.source.data.id + " " + "linkId-" + d.target.data.id
);

// 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.id + "-" + d.target.id);

// 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("id", (d) => "circle-" + d.id)
.attr("class", (d, i) => {
const linksToNode = links.filter((node) => node.target.id == d.id);
const linksFromNode = links.filter((node) => node.source.id == d.id);
let string = "";
for (const link of linksToNode) {
string += "circle-" + link.source.id + " ";
}
for (const link of linksFromNode) {
// this seems not to work...
string += "circle-" + link.target.id + " ";
}
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.title)
.attr("id", (d) => d.id)
.attr("class", (d, i) => {
const linksToNode = links.filter((node) => node.target.id == d.id);
const linksFromNode = links.filter(
(node) => node.source.id == d.id && node.source.id != "index"
);
let string = "";
for (const link of linksToNode) {
string += "nodeId-" + link.source.id + " ";
}
for (const link of linksFromNode) {
string += "nodeId-" + link.target.id + " ";
}
return string;
})
.on("mouseover", function (d, i) {
const id = this.getAttribute("id");
const node = root.descendants().find((d) => d.id === id);
const ancestors = node.ancestors();
d3.select(this).attr("font-weight", "bold").attr("fill", "red");
d3.select("#circle-" + id).attr("fill", "red");
d3.selectAll(".circle-" + id).attr("fill", "red");
d3.selectAll(".nodeId-" + id)
.attr("font-weight", "bold")
.attr("fill", "red");
d3.selectAll(".linkId-" + id)
.attr("stroke", "red")
.attr("stroke-opacity", 1)
.attr("stroke-width", 1.5); // 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].id);
d3.select(
".radialLinkId-" + ancestors[i + 1].id + "-" + ancestors[i].id
)
.attr("stroke", "red")
.attr("stroke-opacity", 1)
.attr("stroke-width", 1.5);
d3.select("#" + ancestors[i + 1].id)
.attr("font-weight", "bold")
.attr("fill", "red");
d3.select("#circle-" + ancestors[i + 1].id).attr("fill", "red");
}
})
.on("mouseout", function (d, i) {
const id = this.getAttribute("id");
const node = root.descendants().find((d) => d.id === id);
const ancestors = node.ancestors();
d3.select(this)
.attr("font-weight", "normal")
.attr("fill", "currentColor");
d3.select("#circle-" + id).attr("fill", node.children ? "#555" : "#999");
d3.selectAll(".circle-" + id).attr("fill", "#999");
d3.selectAll(".nodeId-" + id)
.attr("font-weight", "normal")
.attr("fill", "currentColor");
d3.selectAll(".linkId-" + id)
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5);
for (let i = 0; i < ancestors.length; i++) {
console.log(i, ancestors[i], ancestors[i].id);
d3.select(
".radialLinkId-" + ancestors[i + 1].id + "-" + ancestors[i].id
)
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5);
d3.select("#" + ancestors[i + 1].id)
.attr("font-weight", "normal")
.attr("fill", "currentColor");
d3.select("#circle-" + ancestors[i + 1].id).attr(
"fill",
ancestors[i + 1].children ? "#555" : "#999"
);
}
});

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 = FileAttachment("data.json").json()
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