Sankey 2

by bizamajig

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 getLinkID(d){
    return "link-" + 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, getLinkID);

grads.enter().append("linearGradient")
        .attr("id", getLinkID)
        .attr("gradientUnits", "objectBoundingBox"); 
                //stretch to fit

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) 
    });

// add in the links
var link = svg.append("g").selectAll(".link")
   ...