Skip to content

Instantly share code, notes, and snippets.

@cirofdo
Last active November 7, 2022 21:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cirofdo/f73a2a0625bb803179f3905fe7624e22 to your computer and use it in GitHub Desktop.
Save cirofdo/f73a2a0625bb803179f3905fe7624e22 to your computer and use it in GitHub Desktop.
Collapsible Sankey Diagram Aligned Left

This is a sankey diagram aligned left based on Vasco Asturiano great work.

The collapsible option was a great work made by sheilak

The gradient coloring was done based on AmeliaBR answer on StackOverflow

// https://github.com/vasturiano/d3-sankey Version 0.4.2.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array'), require('d3-collection'), require('d3-interpolate')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-interpolate'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3));
}(this, (function (exports,d3Array,d3Collection,d3Interpolate) { 'use strict';
var sankey = function() {
var sankey = {},
nodeWidth = 24,
nodePadding = 8,
size = [1, 1],
align = 'justify', // left, right, center or justify
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.align = function(_) {
if (!arguments.length) return align;
align = _.toLowerCase();
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 = d3Interpolate.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(
d3Array.sum(node.sourceLinks, value),
d3Array.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,
reverse = (align === 'right'); // Reverse traversal direction
while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function(node) {
node.x = x;
node.dx = nodeWidth;
node[reverse ? 'targetLinks' : 'sourceLinks'].forEach(function(link) {
var nextNode = link[reverse ? 'source' : 'target'];
if (nextNodes.indexOf(nextNode) < 0) {
nextNodes.push(nextNode);
}
});
});
remainingNodes = nextNodes;
++x;
}
if (reverse) {
// Flip nodes horizontally
nodes.forEach(function(node) {
node.x *= -1;
node.x += x - 1;
});
}
if (align === 'center') {
moveSourcesRight();
}
if (align === 'justify') {
moveSinksRight(x);
}
scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
}
function moveSourcesRight() {
nodes.slice()
// Pack nodes from right to left
.sort(function(a, b) { return b.x - a.x; })
.forEach(function(node) {
if (!node.targetLinks.length) {
node.x = d3Array.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 = d3Collection.nest()
.key(function(d) { return d.x; })
.sortKeys(d3Array.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 = d3Array.min(nodesByBreadth, function(nodes) {
return (size[1] - (nodes.length - 1) * nodePadding) / d3Array.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) {
nodes.forEach(function(node) {
if (node.targetLinks.length) {
var y = d3Array.sum(node.targetLinks, weightedSource) / d3Array.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 = d3Array.sum(node.sourceLinks, weightedTarget) / d3Array.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;
};
exports.sankey = sankey;
Object.defineProperty(exports, '__esModule', { value: true });
})));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Sankey Chart for visualizing churn</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="chart_15"></div>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript" src="d3-sankey.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
source target value
lead_15 S 300
lead_15 N 700
S INIB 150
S N_INIB 150
INIB INIB_A 50
INIB INIB_B 50
INIB INIB_C 50
N PAGOU 500
PAGOU ESPONTANEO 300
N N_PAGOU 200
PAGOU POS_ACORDO 200
POS_ACORDO POS_ACORDO_A 25
POS_ACORDO POS_ACORDO_B 100
POS_ACORDO POS_ACORDO_C 75
N_PAGOU N_PAGOU_A 100
N_PAGOU N_PAGOU_B 50
N_PAGOU N_PAGOU_C 50
var units = "Widgets";
// Dimensions
var w = 960,
h = 400;
var margin = {top: 10, right: 10, bottom: 10, left:25},
width = w - margin.left - margin.right,
height = h - margin.top - margin.bottom;
// format variables
var formatNumber = d3.format(",.0f"), // zero decimal places
format = function(d) { return formatNumber(d) + " " + units; },
color = d3.scaleOrdinal(d3.schemeCategory20);
// SVG Canvas
var svg = d3.select("#chart_15").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(20)
.nodePadding(40)
.size([width, height])
.align("left");
var path = sankey.link();
// for gradient coloring
var defs = svg.append("defs");
var graph;
// Read data
d3.csv("sankey.csv", function(error, data) {
// Define graph
graph = {"nodes" : [], "links" : []};
// Arrange .csv data file
data.forEach(function (d) {
graph.nodes.push({ "name": d.source });
graph.nodes.push({ "name": d.target });
graph.links.push({ "source": d.source,
"target": d.target,
"value": +d.value });
});
// return only the distinct / unique nodes
graph.nodes = d3.keys(d3.nest()
.key(function (d) { return d.name; })
.object(graph.nodes));
// Properties for nodes to keep track of whether they are collapsed and how many of their parent nodes are collapsed
graph.nodes.forEach(function (d, i) {
graph.nodes[i] = { "name": d };
graph.nodes[i].collapsing = 0; // count of collapsed parent nodes
graph.nodes[i].collapsed = false;
graph.nodes[i].collapsible = false;
});
// links point to the whole source or target node rather than the index because we need the source nodes for filtering.
//I also set all target nodes are collapsible.
graph.links.forEach(function(e) {
e.source = graph.nodes.filter(function(n) {
return n.name === e.source;
})[0],
e.target = graph.nodes.filter(function(n) {
return n.name === e.target;
})[0];
e.target.collapsible = true;
});
update();
});
var nodes, links;
function update() {
nodes = graph.nodes.filter(function(d) {
// return nodes with no collapsed parent nodes
return d.collapsing == 0;
});
links = graph.links.filter(function(d) {
// return only links where source and target are visible
return d.source.collapsing == 0 && d.target.collapsing == 0;
});
// Sankey properties
sankey
.nodes(nodes)
.links(links)
.layout(32);
// I need to call the function that renders the sankey, remove and call it again,
// or the gradient coloring doesn't apply (I don't know why)
sankeyGen();
svg.selectAll("g").remove();
sankey.align("left").layout(32);
sankeyGen();
}
function sankeyGen() {
/* function that will create a unique id for your gradient from a link data object.
It's also a good idea to give a name to the function for determining node colour */
// define utility functions
function getGradID(d) {
return "linkGrad-" + d.source.name + "-" + d.target.name;
};
function nodeColor(d) {
return d.color = color(d.name.replace(/ .*/, ""));
};
// create gradients for the links
var grads = defs.selectAll("linearGradient")
.data(links, getGradID);
grads.enter().append("linearGradient")
.attr("id", getGradID)
.attr("gradientUnits", "userSpaceOnUse");
function positionGrads() {
grads.attr("x1", function(d){return d.source.x;})
.attr("y1", function(d){return d.source.y;})
.attr("x2", function(d){return d.target.x;})
.attr("y2", function(d){return d.target.y;});
}
positionGrads();
grads.html("") //erase any existing <stop> elements on update
.append("stop")
.attr("offset", "0%")
.attr("stop-color", function(d) {
return nodeColor( (+d.source.x <= +d.target.x)? d.source: d.target) ;
});
grads.append("stop")
.attr("offset", "100%")
.attr("stop-color", function(d) {
return nodeColor( (+d.source.x > +d.target.x)? d.source: d.target)
});
//////////////////////////////////////////////////////////////////////
//
////// LINKS //////
//
// ENTER the links
console.log(links)
var link = svg.append("g").selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke", function(d) {
return "url(#" + getGradID(d) + ")";
})
//.style("stroke", function(d) {
// return d.source.color;
//})
//.style("stroke", "#3f51b5")
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
// add the link titles
link.append("title")
.text(function(d) {
return d.source.name + " → " + d.target.name + "\n" + format(d.value);
});
////// NODES //////
//
// ENTER the nodes
var node = svg.append("g").selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", function(d) { return "node " + d.name; })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
//// Drag the nodes ////
/*.call(d3.drag()
.subject(function(d) { return d; })
.on("start", function() { this.parentNode.appendChild(this);})
.on("drag", dragmove)
);*/
// add the rectangles for the nodes
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", function(d) {
return color(d.name.replace(/ .*/, ""));
// return d3.rgb(d.color).darker(2);
})
.append("title")
.text(function(d) { return d.name + "\n" + format(d.value); });
// Scale for text
var graphValues = new Array(nodes.length-1);
for (var i = 0; i <= nodes.length-1; i++) {
graphValues[i] = nodes[i].value;
};
var textScale = d3.scaleLinear()
.domain([d3.min(graphValues), d3.max(graphValues)])
.range([10, 20]);
// add in the title for the nodes
node.append("text")
.style("font-size", function(d) { return textScale(d.value); })
.style("font-family", "Helvetica")
.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; })
// Selects the main node
.filter(function(d) { return d.x < 1; })
.attr("x", function(d) { return - d.dy / 2 })
.attr("y", -12)
.attr("text-anchor", "middle");
// the function for moving the nodes
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);
}
node.on('click', click);
function click(d) {
if (d3.event.defaultPrevented) return;
if (d.collapsible) {
// If it was visible, it will become collapsed so we should decrement child nodes count
// If it was collapsed, it will become visible so we should increment child nodes count
var inc = d.collapsed ? -1 : 1;
recurse(d);
function recurse(sourceNode){
//check if link is from this node, and if so, collapse
graph.links.forEach(function(l) {
if (l.source.name === sourceNode.name){
l.target.collapsing += inc;
recurse(l.target);
}
});
}
d.collapsed = !d.collapsed; // toggle state of node
}
update();
}
};
.node rect {
fill-opacity: .9;
shape-rendering: crispEdges;
}
.node text {
pointer-events: none;
}
.node.lead_15 text {
-webkit-transform: rotate(-90deg);
}
.link {
fill: none;
stroke: #000;
stroke-opacity: .2;
}
.link:hover {
stroke-opacity: .5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment