Published
Edited
May 24, 2019
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height))
.style("width", "100%")
.style("height", "auto");

const {nodes, links} = sankey(sankeyData[0]);

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", d => color(d.name))
.append("title")
.text(d => `${d.name}\n${format(10)}`);

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.target.name))
.attr("stroke-width", d => Math.max(1, d.width));

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

svg.append("g")
.style("font", "20px sans-serif")
.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
sankey = {
const sankey = d3.sankey()
//.nodeAlign(d3[`sankey${align[0].toUpperCase()}${align.slice(1)}`])
.nodeWidth(50)
.nodePadding(200)
.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
// color = {
// if (name === "Will Not Pay")
// return name => "#111";
// else
// return name => "#ccc";
// //return name => color(name.replace(/ .*/, ""));
// }

color = d3.scaleOrdinal(["Granted", "Denied", "Will Pay", "Will Not Pay"], ["#1f77b4","#ff7f0e","#1f77b4","#ff7f0e"]).unknown("#ccc")
Insert cell
data = d3.json("https://gist.githubusercontent.com/mbostock/ca9a0bb7ba204d12974bca90acc507c0/raw/398136b7db83d7d7fd89181b080924eb76041692/energy.json")
Insert cell
sankeyData = [{
"nodes": [
{
"name": "Granted",
},
{
"name": "Denied",
},
{
"name": "Will Pay",
},
{
"name": "Will Not Pay",
}
],
"links": [
{
"source": 0, // granted
"target": 2, // will pay
"value": 590
},
{
"source": 0, // granted
"target": 3, // will not pay
"value": 55
},
{
"source": 1, // denied
"target": 2, // will pay
"value": 45
},
{
"source": 1, // denied
"target": 3, // will not pay
"value": 310
}
]
}]
Insert cell
format = {

return d => d;
}
Insert cell
sankeyData[0].nodes
Insert cell
width = 975
Insert cell
height = 600
Insert cell
d3 = require("d3@5", "d3-sankey@0.12")
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