JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
</style>
<script type="text/javascript" src="https://d3js.org/d3.v5.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/d3-sankey@0.7.1/build/d3-sankey.js"></script>
</head>
<body>
<select id="colorSelect">
<option value=input>Color by input
<option value=output>Color by output
<option value=path selected>Color by input-output
</select>
<div id='container'>
<svg id='chart' xmlns="http://www.w3.org/2000/svg" ></svg>
</div>
</body>
JavaScript
const width = 964;
const height = 600;
let edgeColor = 'path';
const _sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.extent([[1, 1], [width - 1, height - 5]]);
const sankey = ({nodes, links}) => _sankey({
nodes: nodes.map(d => Object.assign({}, d)),
links: links.map(d => Object.assign({}, d))
});
const f = d3.format(",.0f");
const format = d => `${f(d)} TWh`;
const _color = d3.scaleOrdinal(d3.schemeCategory10);
const color = name => _color(name.replace(/ .*/, ""));
const svg = d3.select('#chart')
.attr("viewBox", `0 0 ${width} ${height}`)
.style("width", "100%")
.style("height", "auto");
d3.json("https://gist.githubusercontent.com/mbostock/ca9a0bb7ba204d12974bca90acc507c0/raw/398136b7db83d7d7fd89181b080924eb76041692/energy.json").then(data => {
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", d => color(d.name))
.append("title")
.text(d => `${d.name}\n${format(d.value)}`);
const link = svg.append("g")
.attr("fill", "none")
.attr("stroke-opacity", 0.5)
.selectAll("g")
.data(links)
.join("g")
.style("mix-blend-mode", "multiply");
const select = document.querySelector('#colorSelect');
select.onchange = () => {
edgeColor = select.value;
update();
};
function update() {
if (edgeColor === "path") {
const gradient = link.append("linearGradient")
.attr("id", (d,i) => {
// (d.uid = DOM.uid("link")).id
const id = `link-${i}`;
d.uid = `url(#${id})`;
return id;
})
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", d => d.source.x1)
.attr("x2", d => d.target.x0);
gradient.append("stop")
.attr("offset", "0%")
...