Published
Edited
Mar 13, 2022
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);

const chords = chord(matrix);

const textId = DOM.uid("text");

svg.append("path")
.attr("id", textId.id)
.attr("fill", "none")
.attr("d", d3.arc()({outerRadius, startAngle: 0, endAngle: 2 * Math.PI}));

svg.append("g")
.attr("fill-opacity", 0.75)
.selectAll("g")
.data(chords)
.join("path")
.attr("d", ribbon)
.attr("fill", d => color(names[d.target.index]))
.style("mix-blend-mode", "multiply")
.append("title")
.text(d => `${names[d.source.index]} owes ${names[d.target.index]} ${formatValue(d.source.value)}`);

svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(chords.groups)
.join("g")
.call(g => g.append("path")
.attr("d", arc)
.attr("fill", d => color(names[d.index]))
.attr("stroke", "#fff"))
.call(g => g.append("text")
.attr("dy", -3)
.append("textPath")
.attr("xlink:href", textId.href)
.attr("startOffset", d => d.startAngle * outerRadius)
.text(d => names[d.index]))
.call(g => g.append("title")
.text(d => `${names[d.index]}
owes ${formatValue(d3.sum(matrix[d.index]))}
is owed ${formatValue(d3.sum(matrix, row => row[d.index]))}`));

return svg.node();
}
Insert cell
// data = d3.csvParse(await FileAttachment("chord_diagram_df.csv.csv").text(), d3.autoType)
Insert cell
data = FileAttachment("chord_diagram_df@1.csv").csv()
Insert cell
names = Array.from(new Set(data.flatMap(d => [d.country_0, d.country_1])))
Insert cell
matrix = {
const index = new Map(names.map((name, i) => [name, i]));
const matrix = Array.from(index, () => new Array(names.length).fill(0));
for (const {country_0, country_1, value} of data) matrix[index.get(country_0)][index.get(country_1)] += value;
return matrix;
}
Insert cell
chord = d3.chordDirected()
.padAngle(12 / innerRadius)
.sortSubgroups(d3.descending)
.sortChords(d3.descending)
Insert cell
arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
Insert cell
ribbon = d3.ribbonArrow()
.radius(innerRadius - 0.5)
.padAngle(1 / innerRadius)
Insert cell
color = d3.scaleOrdinal(names, d3.schemeCategory10)
Insert cell
formatValue = x => `${x.toFixed(0)}B`
Insert cell
outerRadius = innerRadius + 6
Insert cell
innerRadius = Math.min(width, height) * 0.5 - 20
Insert cell
width = 840
Insert cell
height = width
Insert cell
d3 = require("d3@6")
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