Skip to content

Instantly share code, notes, and snippets.

@ashleyignatius
Forked from emeeks/d3.sankey.js
Last active December 18, 2015 15:46
Show Gist options
  • Save ashleyignatius/20a74ac94fcc176ced18 to your computer and use it in GitHub Desktop.
Save ashleyignatius/20a74ac94fcc176ced18 to your computer and use it in GitHub Desktop.
Minnesota's Western Lake Superior Drainage

Fixed width edges in Sankey where flow value is indicated by number of particles. Typically a sankey diagram uses the width of the edges to indicate value of flow but here it's done entirely with particles. Drag the nodes to adjust the paths of the particles.

Other examples of sankeys with particles:

d3.sankey = function() {
var sankey = {},
nodeWidth = 24,
nodePadding = 8,
size = [1, 1],
nodes = [],
links = [];
sankey.nodeWidth = function(_) {
if (!arguments.length) return nodeWidth;
nodeWidth = +_;
return sankey;
};
sankey.nodePadding = function(_) {
if (!arguments.length) return nodePadding;
nodePadding = +_;
return sankey;
};
sankey.nodes = function(_) {
if (!arguments.length) return nodes;
nodes = _;
return sankey;
};
sankey.links = function(_) {
if (!arguments.length) return links;
links = _;
return sankey;
};
sankey.size = function(_) {
if (!arguments.length) return size;
size = _;
return sankey;
};
sankey.layout = function(iterations) {
computeNodeLinks();
computeNodeValues();
computeNodeBreadths();
computeNodeDepths(iterations);
computeLinkDepths();
return sankey;
};
sankey.relayout = function() {
computeLinkDepths();
return sankey;
};
sankey.link = function() {
var curvature = .5;
function link(d) {
var x0 = d.source.x + d.source.dx,
x1 = d.target.x,
xi = d3.interpolateNumber(x0, x1),
x2 = xi(curvature),
x3 = xi(1 - curvature),
y0 = d.source.y + d.sy + d.dy / 2,
y1 = d.target.y + d.ty + d.dy / 2;
return "M" + x0 + "," + y0
+ "C" + x2 + "," + y0
+ " " + x3 + "," + y1
+ " " + x1 + "," + y1;
}
link.curvature = function(_) {
if (!arguments.length) return curvature;
curvature = +_;
return link;
};
return link;
};
// Populate the sourceLinks and targetLinks for each node.
// Also, if the source and target are not objects, assume they are indices.
function computeNodeLinks() {
nodes.forEach(function(node) {
node.sourceLinks = [];
node.targetLinks = [];
});
links.forEach(function(link) {
var source = link.source,
target = link.target;
if (typeof source === "number") source = link.source = nodes[link.source];
if (typeof target === "number") target = link.target = nodes[link.target];
source.sourceLinks.push(link);
target.targetLinks.push(link);
});
}
// Compute the value (size) of each node by summing the associated links.
function computeNodeValues() {
nodes.forEach(function(node) {
node.value = Math.max(
d3.sum(node.sourceLinks, value),
d3.sum(node.targetLinks, value)
);
});
}
// Iteratively assign the breadth (x-position) for each node.
// Nodes are assigned the maximum breadth of incoming neighbors plus one;
// nodes with no incoming links are assigned breadth zero, while
// nodes with no outgoing links are assigned the maximum breadth.
function computeNodeBreadths() {
var remainingNodes = nodes,
nextNodes,
x = 0;
while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function(node) {
node.x = x;
node.dx = nodeWidth;
node.sourceLinks.forEach(function(link) {
if (nextNodes.indexOf(link.target) < 0) {
nextNodes.push(link.target);
}
});
});
remainingNodes = nextNodes;
++x;
}
//
moveSinksRight(x);
scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
}
function moveSourcesRight() {
nodes.forEach(function(node) {
if (!node.targetLinks.length) {
node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
}
});
}
function moveSinksRight(x) {
nodes.forEach(function(node) {
if (!node.sourceLinks.length) {
node.x = x - 1;
}
});
}
function scaleNodeBreadths(kx) {
nodes.forEach(function(node) {
node.x *= kx;
});
}
function computeNodeDepths(iterations) {
var nodesByBreadth = d3.nest()
.key(function(d) { return d.x; })
.sortKeys(d3.ascending)
.entries(nodes)
.map(function(d) { return d.values; });
//
initializeNodeDepth();
resolveCollisions();
for (var alpha = 1; iterations > 0; --iterations) {
relaxRightToLeft(alpha *= .99);
resolveCollisions();
relaxLeftToRight(alpha);
resolveCollisions();
}
function initializeNodeDepth() {
var ky = d3.min(nodesByBreadth, function(nodes) {
return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
});
nodesByBreadth.forEach(function(nodes) {
nodes.forEach(function(node, i) {
node.y = i;
node.dy = node.value * ky;
});
});
links.forEach(function(link) {
link.dy = link.value * ky;
});
}
function relaxLeftToRight(alpha) {
nodesByBreadth.forEach(function(nodes, breadth) {
nodes.forEach(function(node) {
if (node.targetLinks.length) {
var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedSource(link) {
return center(link.source) * link.value;
}
}
function relaxRightToLeft(alpha) {
nodesByBreadth.slice().reverse().forEach(function(nodes) {
nodes.forEach(function(node) {
if (node.sourceLinks.length) {
var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedTarget(link) {
return center(link.target) * link.value;
}
}
function resolveCollisions() {
nodesByBreadth.forEach(function(nodes) {
var node,
dy,
y0 = 0,
n = nodes.length,
i;
// Push any overlapping nodes down.
nodes.sort(ascendingDepth);
for (i = 0; i < n; ++i) {
node = nodes[i];
dy = y0 - node.y;
if (dy > 0) node.y += dy;
y0 = node.y + node.dy + nodePadding;
}
// If the bottommost node goes outside the bounds, push it back up.
dy = y0 - nodePadding - size[1];
if (dy > 0) {
y0 = node.y -= dy;
// Push any overlapping nodes back up.
for (i = n - 2; i >= 0; --i) {
node = nodes[i];
dy = node.y + node.dy + nodePadding - y0;
if (dy > 0) node.y -= dy;
y0 = node.y;
}
}
});
}
function ascendingDepth(a, b) {
return a.y - b.y;
}
}
function computeLinkDepths() {
nodes.forEach(function(node) {
node.sourceLinks.sort(ascendingTargetDepth);
node.targetLinks.sort(ascendingSourceDepth);
});
nodes.forEach(function(node) {
var sy = 0, ty = 0;
node.sourceLinks.forEach(function(link) {
link.sy = sy;
sy += link.dy;
});
node.targetLinks.forEach(function(link) {
link.ty = ty;
ty += link.dy;
});
});
function ascendingSourceDepth(a, b) {
return a.source.y - b.source.y;
}
function ascendingTargetDepth(a, b) {
return a.target.y - b.target.y;
}
}
function center(node) {
return node.y + node.dy / 2;
}
function value(link) {
return link.value;
}
return sankey;
};
{"nodes":[
{"name":"0 Arrow River (0401010101)"},
{"name":"1 Baptism River (0401010111)"},
{"name":"2 Beaver River-Frontal Lake Superior (0401010201)"},
{"name":"3 Black River (0401030103)"},
{"name":"4 Boulder Lake Reservoir (0401020203)"},
{"name":"5 Brule River (0401010104)"},
{"name":"6 Cascade River-Frontal Lake Superior (0401010106)"},
{"name":"7 City of Duluth-Frontal Lake Superior (0401010204)"},
{"name":"8 Cross River-Frontal Lake Superior (0401010109)"},
{"name":"9 Devil Track River-Frontal Lake Superior (0401010105)"},
{"name":"10 East Savanna River (0401020103)"},
{"name":"11 Embarrass River (0401020103)"},
{"name":"12 Fish Lake Reservoir (0401020205)"},
{"name":"13 Floodwood River (0401020110)"},
{"name":"14 Gooseberry River-Frontal Lake Superior (0401010202)"},
{"name":"15 Headwaters Cloquet River (0401020201)"},
{"name":"16 Knife River-Frontal Lake Superior (0401020201)"},
{"name":"17 Manitou River-Frontal Lake Superior (0401010110)"},
{"name":"18 Midway River (0401020114)"},
{"name":"19 Mud Hen Creek (0401020107"},
{"name":"20 Partridge River (0401020101"},
{"name":"21 Poplar River-Frontal Lake Superior (0401010107)"},
{"name":"22 South Fork Nemidji River (0401030101)"},
{"name":"23 Stoney Brook (0401020112)"},
{"name":"24 Swan River (0401020106)"},
{"name":"25 Temperance River (0401010108)"},
{"name":"26 Upper Nemadji River (0401030102)"},
{"name":"27 Upper Whiteface River (0401020109)"},
{"name":"28 West Branch Cloquet River (0401020202)"},
{"name":"29 West Two River (0401020105)"},
{"name":"30 Headwaters St. Louis River (0401020102)"},
{"name":"31 Pigeon River (0401010102)"},
{"name":"32 St. Louis River (0401020116)"},
{"name":"33 Cloquet River (0401020206)"},
{"name":"34 Lower Whiteface River (0401020109)"},
{"name":"35 Middle Nemadji River (0401030104)"},
{"name":"36 Island Lake Reservoir-Cloquet River (0401020204)"},
{"name":"37 Lower Nemadji River (0401030105)"},
{"name":"38 Thompson Reservoir-St. Louis River (0401020115)"},
{"name":"39 Sand Creek-St. Louis River (0401020107)"},
{"name":"40 Artichoke River-St. Louis River (0401020113)"},
{"name":"41 Lake Superior (0402030000)"},
{"name":"42 Flute Reed River (0401010103)"}
],
"links":[
{"source":0,"target":31,"value":4.52},
{"source":9,"target":41,"value":21.28},
{"source":10,"target":40,"value":19},
{"source":11,"target":39,"value":29.55},
{"source":12,"target":33,"value":11.8},
{"source":13,"target":40,"value":33.01},
{"source":14,"target":41,"value":27.89},
{"source":15,"target":36,"value":28.45},
{"source":16,"target":41,"value":27.48},
{"source":17,"target":41,"value":21.75},
{"source":18,"target":38,"value":10.35},
{"source":1,"target":41,"value":21.57},
{"source":19,"target":39,"value":15.78},
{"source":20,"target":30,"value":24.32},
{"source":21,"target":41,"value":23.62},
{"source":22,"target":35,"value":13.9},
{"source":23,"target":40,"value":15.71},
{"source":24,"target":39,"value":38.93},
{"source":25,"target":41,"value":28.73},
{"source":26,"target":35,"value":22.41},
{"source":27,"target":34,"value":40.85},
{"source":28,"target":36,"value":16.47},
{"source":2,"target":41,"value":23.46},
{"source":29,"target":39,"value":12.35},
{"source":30,"target":39,"value":32.58},
{"source":31,"target":41,"value":31.7},
{"source":32,"target":37,"value":25},
{"source":33,"target":38,"value":28.78},
{"source":34,"target":40,"value":50.59},
{"source":35,"target":37,"value":11.71},
{"source":36,"target":33,"value":27.58},
{"source":37,"target":41,"value":11.29},
{"source":38,"target":32,"value":29.94},
{"source":3,"target":37,"value":14.46},
{"source":39,"target":40,"value":53.5},
{"source":40,"target":38,"value":26.55},
{"source":4,"target":36,"value":10.5},
{"source":5,"target":41,"value":41.34},
{"source":6,"target":41,"value":21.38},
{"source":7,"target":41,"value":18.42},
{"source":8,"target":41,"value":16.87},
{"source":42,"target":41,"value":14.62}
]}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sankey Particles</title>
<style>
.node rect {
cursor: move;
fill-opacity: .9;
shape-rendering: crispEdges;
}
.node text {
pointer-events: none;
text-shadow: 0 1px 0 #fff;
}
.link {
fill: none;
stroke: #000;
stroke-opacity: .15;
}
.link:hover {
stroke-opacity: .25;
}
svg {
position: absolute;
}
canvas {
position: absolute;
}
</style>
</head>
<body>
<canvas width="1000" height="1000" ></canvas>
<svg width="1000" height="1000" ></svg>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8" type="text/javascript"></script>
<script src="d3.sankey.js" charset="utf-8" type="text/javascript"></script>
<script type="text/javascript">
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatNumber = d3.format(",.0f"),
format = function(d) { return formatNumber(d) + " TWh"; },
color = d3.scale.category20();
var svg = d3.select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
var freqCounter = 1;
d3.json("energy.json", function(energy) {
energy.links.forEach(function (d) {
d.o_value = d.value;
d.value = 1;
})
sankey
.nodes(energy.nodes)
.links(energy.links)
.layout(32);
var link = svg.append("g").selectAll(".link")
.data(energy.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.o_value); });
var node = svg.append("g").selectAll(".node")
.data(energy.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
.style("stroke", "none")
.append("title")
.text(function(d) { return d.name + "\n" + format(d.o_value); });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
var linkExtent = d3.extent(energy.links, function (d) {return d.o_value});
var frequencyScale = d3.scale.linear().domain(linkExtent).range([0.05,1]);
var particleSize = d3.scale.linear().domain(linkExtent).range([1,5]);
energy.links.forEach(function (link) {
link.freq = frequencyScale(link.o_value);
link.particleSize = 2;
link.particleColor = d3.scale.linear().domain([0,1])
.range([link.source.color, link.target.color]);
})
var t = d3.timer(tick, 1000);
var particles = [];
function tick(elapsed, time) {
particles = particles.filter(function (d) {return d.current < d.path.getTotalLength()});
d3.selectAll("path.link")
.each(
function (d) {
// if (d.freq < 1) {
for (var x = 0;x<2;x++) {
var offset = (Math.random() - .5) * (d.dy - 4);
if (Math.random() < d.freq) {
var length = this.getTotalLength();
particles.push({link: d, time: elapsed, offset: offset, path: this, length: length, animateTime: length, speed: 0.5 + (Math.random())})
}
}
// }
/* else {
for (var x = 0; x<d.freq; x++) {
var offset = (Math.random() - .5) * d.dy;
particles.push({link: d, time: elapsed, offset: offset, path: this})
}
} */
});
particleEdgeCanvasPath(elapsed);
}
function particleEdgeCanvasPath(elapsed) {
var context = d3.select("canvas").node().getContext("2d")
context.clearRect(0,0,1000,1000);
context.fillStyle = "gray";
context.lineWidth = "1px";
for (var x in particles) {
var currentTime = elapsed - particles[x].time;
// var currentPercent = currentTime / 1000 * particles[x].path.getTotalLength();
particles[x].current = currentTime * 0.15 * particles[x].speed;
var currentPos = particles[x].path.getPointAtLength(particles[x].current);
context.beginPath();
context.fillStyle = particles[x].link.particleColor(0);
context.arc(currentPos.x,currentPos.y + particles[x].offset,particles[x].link.particleSize,0,2*Math.PI);
context.fill();
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment