Sankey 2
by ashishsingh
CSS
.node rect {
cursor: move;
}
.node text {
pointer-events: none;
}
JavaScript
var units = "Widgets";
var margin = {
top: 10,
right: 10,
bottom: 10,
left: 10
},
width = 640 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var formatNumber = d3.format(",.0f"), // zero decimal places
format = function (d) {
return formatNumber(d) + " " + units;
},
color = d3.scale.category20();
// append the svg canvas to the page
var svg = d3.select("body").append("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 defs = svg.append("defs");
// Set the sankey diagram properties
var sankey = d3sankey()
.nodeWidth(17)
.nodePadding(27)
.size([width, height]);
var path = sankey.link();
// load the data
var graph = getData();
sankey.nodes(graph.nodes)
.links(graph.links)
.layout(32);
// 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(graph.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%")
...