Published
Edited
Jul 7, 2021
1 fork
Insert cell
md`# Test sankey`
Insert cell
data = {
var nodes = [{name: "A1", year: 1}, {name: "B1", year: 1}, {name: "A2", year: 2}, {name: "B2", year: 2}],
links = [
{source: "A1", target: "A2", value: 150},
{source: "A1", target: "B2", value: 50},
{source: "B1", target: "A2", value: 100},
{source: "B1", target: "B2", value: 200}
];
return {
nodes: nodes,
links: links
}
}
Insert cell
sankey = {
const sankey = d3.sankey()
.nodeId(d => d.name)
.nodeWidth(15)
.nodePadding(10)
.extent([[1, 5], [width - 1, height - 5]]);
return ({nodes, links}) => sankey({
nodes: nodes.map(d => Object.assign({}, d)),
links: links.map(d => Object.assign({}, d))
});
}
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

const {nodes, links} = sankey(data);

svg.append("g")
.attr("stroke", "#000")
.selectAll("rect")
.data(nodes)
.join("rect")
.attr("x", d => d.x0)
.attr("y", d => d.y0)
.attr("height", d => d.y1 - d.y0)
.attr("width", d => d.x1 - d.x0)
.attr("fill", color)
.append("title")
.text(d => d.name);

const link = svg.append("g")
.attr("fill", "none")
.attr("stroke-opacity", 0.5)
.selectAll("g")
.data(links)
.join("g")
.style("mix-blend-mode", "multiply");

link.append("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", d => color(d.source))
.attr("stroke-width", d => Math.max(1, d.width));

link.append("title")
.text(d => `${d.source.name} → ${d.target.name}\n${d.value}`);

svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("text")
.data(nodes)
.join("text")
.attr("x", d => d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6)
.attr("y", d => (d.y1 + d.y0) / 2)
.attr("dy", "0.35em")
.attr("text-anchor", d => d.x0 < width / 2 ? "start" : "end")
.text(d => d.name);

return svg.node();
}
Insert cell
color = function(a) {
return "black";
}
Insert cell
Insert cell
width = 600
Insert cell
height = 400
Insert cell
d3 = require("d3", "d3-sankey")
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