Skip to content

Instantly share code, notes, and snippets.

@ajmistu
Last active July 16, 2017 21:34
Show Gist options
  • Select an option

  • Save ajmistu/c4f710d5cf11b7ebafe640f242b88142 to your computer and use it in GitHub Desktop.

Select an option

Save ajmistu/c4f710d5cf11b7ebafe640f242b88142 to your computer and use it in GitHub Desktop.
Collapsible Sankey Diagram Aligned Left (Sample 3)
license: mit
// 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>
<button type="button" id="start" onclick="window.location.reload()">Start</button>
<button type="button" id="reset" >Reset</button>
<!-- <button type="button" id="reset">Reset</button> -->
<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
omelet 1 2
tostada 1 2
burrito 1 2
hummus 2 2
fondue 3 2
sugar 4 2
lemonade 5 2
screwdriver 6 2
champagne 6 2
martini 7 2
egg yolk 8 2
1 2 2
2 3 2
3 4 2
4 5 2
5 6 2
6 7 2
7 8 2
// d3.csv("sankey.csv", function(rows) {
// console.log(rows);
// var parents = [];
// rows.forEach(function(row) {
// // if we don't have this parent yet, add a blank node
// if (parents[row.target] === undefined) {
// parents[row.target] = {level: row.target, children: []};
// }
// parents[row.target].children.push({value: row.source});
// });
// for (var i = parents.length - 1; i > 1; i--) {
// parents[i].children.push(parents[i-1]);
// }
// var root = parents[parents.length - 1];
// // console.log(parents[parents.length - 1]);
// // console.log(JSON.stringify(parents[parents.length-1]));
// // remove undefined items
// parents = parents.filter(function(d) { return true; });
// var svg = d3.select('svg').append('g')
// .attr('transform', 'translate(20,20)');
// var width = 600;
// var categoryBands = d3.scaleBand()
// .range([0, width - -130])
// .domain(parents.map(function(d) { return d.level; }));
// var headers = svg.append('g')
// .attr('class', 'headers');
// var level = headers.selectAll("g.level")
// .data(parents)
// .enter().append('g')
// .attr('class', 'level')
// .attr('transform',
// function(d,i) { return 'translate(' + categoryBands(d.level) + ',0)'; });
// level.append('text')
// // .attr('x', categoryBands.bandwidth() / 2)
// .attr('text-anchor', 'middle')
// .text(function(d) { return d.level; });
// var items = level.selectAll('g.item').data(function(d) { return d.children; })
// .enter().append('g')
// .attr('class', 'item')
// .attr('transform', function(d, i) { return 'translate(0, ' + ((i+1) * 23) + ')'; })
// items.append('text')
// .text(function(d) { return d.value; });
// });
////////////////////
var units = "Widgets";
// Dimensions
var w = 960,
h = 600;
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);
var red = d3.color("hsl(0, 80%, 50%)"); // {h: 0, l: 0.5, s: 0.8, opacity: 1}
// color = d3.scaleOrdinal(d3.schemeCategory10());
// SVG Canvas
var svg = d3.select("#chart_15").append("svg")
.attr("width", w+100)
.attr("height", 700)
.append("g")
.attr("transform", "translate(" + 100+ ","+40+")");
var sankey = d3.sankey()
.nodeWidth(20)
.nodePadding(40)
.size([width-400, 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({ "name1": 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", function(d) { if (d.name == "limpa") { return "red"};})
.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;
});
///////////NODES///////////
//
// ENTER the nodes
var node = svg.append("g").selectAll(".node")
.data(nodes)
.style("fill", "red")
.enter().append("g")
.attr("class", function(d) { return "node " + d.name; })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"
})
// 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(/ .*/, ""));
// })
// Colors all rectangle nodes
// .style("fill", function(d) { return "black";
// })
.style("stroke", function(d) {
// return color(d.name.replace(/ .*/, ""));
// return d3.rgb(d.color).darker(2);
// return "white"
})
.append("title")
.text(function(d) { return d.name + "\n" ; });
// 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", "Times-Roman")
// .style("fill", "red")
.attr("x", function(d) { return d.dx / 2})
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", "1em")
.attr("dx", "-6em")
// .text(function(d) { return d.name; })
.attr("text-anchor", "end")
.attr("transform", null)
// .style("color", "red")
// Selects the main node
.filter(function(d) { return d.x < 1; })
.attr("x", function(d) { return - d.dy / 2 })
.attr("y", 0)
.attr("text-anchor", "start");
// 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);
// }
// d3.selectAll('.node')
// .transition()
// .duration(2150)
// .attr('opacity', 1);
// d3.selectAll('.link')
// .transition()
// .duration(2444)
// .style('opacity', 1);
node.append("text").text(function(d) { return d.name; }).attr("x", function(d) { return d.dx / 2})
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", "1em")
.attr("dx", "-5em")
.filter(function(d) { return d.x < 1; })
.attr("x", function(d) { return - d.dy / 2 })
.attr("y", 0)
// .attr("fill-opacity", 0)
// .transition().delay(3500).duration(1500)
// .attr("fill-opacity", 1);
// .transition()
// // .duration()
.style('opacity',1)
//
// .attr("text-anchor", "start");
// .style("opacity","0")
// .transition("opacity", "0.001");
// node.select(this).append().style("fill", "red");
/////////////////////Onclick functions and calls//////
d3.select("#reset").on("click", reset)
function reset(){
d3.selectALL("graph").style("opacity", 1)
// node.append("text").text(function(d) { return d.name; }).attr("x", function(d) { return d.dx / 2})
// .attr("y", function(d) { return d.dy / 2; })
// .attr("dy", "1em")
// .attr("dx", "-5em")
// .filter(function(d) { return d.x < 1; })
// .attr("x", function(d) { return - d.dy / 2 })
// .attr("y", 0)
// .attr("fill-opacity", 0)
// // .transition().delay(3500).duration(1500)
// .transition().delay(35).duration(1500)
// .attr("fill-opacity", 1);
// // .transition()
// // .duration(2444)
// // .style('opacity',1)
// // // .attr("text-anchor", "start");
// // .remove()
// changeopacity();
};
// function changeopacity(){
// node.append("text").text(function(d) { return d.name; }).attr("x", function(d) { return d.dx / 2})
// .attr("y", function(d) { return d.dy / 2; })
// .attr("dy", "1em")
// .attr("dx", "-5em")
// .filter(function(d) { return d.x < 1; })
// .attr("x", function(d) { return - d.dy / 2 })
// .attr("y", 0)
// .style('opacity', 1) }
// node.on("click",
// click,clicked
// );
function switch1() {
d3.select(this).transition().style("fill", function(d) {return "yellow";}).transition()
};
node.on("click", clicked);
function clicked() {
// if (d3.event.defaultPrevented) return; // dragged
d3.select(this).transition()
.style("fill", function(d){ return "red";})
.transition()
// node.append("rect").style("fill", function(d) { return "#75c165";
// })
.style("")
.style()
d3.select(this).selectAll('.link')
.transition()
.style("fill", "red")
.style('opacity', 0);
// node.on("click", switch1);
// node.append("text").text(function(d) { return d.name; }).attr("x", function(d) { return d.dx / 2})
// .attr("y", function(d) { return d.dy / 2; })
// .attr("dy", "1em")
// .attr("dx", "-5em")
// .filter(function(d) { return d.x < 1; })
// .attr("x", function(d) { return - d.dy / 2 })
// .attr("y", 0)
// .transition()
// .duration(2444)
// .style('opacity', 1)
// .attr("text-anchor", "start");
}
{
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);
d3.select(this).transition()
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;
stroke-width: 2px
/* fill: "blue" */
}
.node text {
pointer-events: none;
/* font-weight: bold ; */
font-size: 16px;
/* fill: blue; */
}
.node.lead_15 text {
-webkit-transform: rotate(-90deg);
}
.link {
fill: none;
stroke: #000;
stroke-opacity: .2;
}
.link:hover {
stroke-opacity: .5;
}
button#refresh {
float:right;
padding:2px;
top: 1;
left: ;
margin-left:5px;
position: absolute;
top: 1%;
left: 2%;
}
button#start {
float:right;
padding:2px;
top: 1;
margin-left:5px;
position: absolute;
top: 5%;
left: 92%;
background-color: #0000FF; /* blue */
border: none;
color: white;
padding: 10px 22px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
button#reset {f
loat:right;
padding:2px;
top: 1;
left: ;
margin-left:5px;
position: absolute;
top: 5%;
left: 80%;
background-color: #0000FF; /* blue */
border: none;
color: white;
padding: 10px 22px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment