Sankey Example

by j_mc_falcon_19

HTML

<!-- Load d3  -->
<script src="https://d3js.org/d3.v4.min.js"></script>

<!-- Load  sankey.js  -->
<script src="https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/sankey.js"></script>


<body>
    <div id="sankey_example"></div>
</body>

CSS

.link {
      fill: none;
      stroke: #000;
      stroke-opacity: .2;
 }
.link:hover {
      stroke-opacity: .5;
 }

JavaScript

window.onload = function(){


 // set the dimensions of the graph and margins
    var margin = {top: 10, right: 10, bottom: 10, left: 10},
        width = (window.screen.availWidth /2) - margin.left - margin.right,
        height = (window.screen.availHeight -100) - margin.top - margin.bottom;
    
    // append the svg object to the body of the page
    var svg = d3.select("#sankey_example").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 + ")");
    
    // Color scale used
    var color = d3.scaleOrdinal(d3.schemeCategory10);
    
    // Set the sankey diagram properties
    var sankey = d3.sankey()
        .nodeWidth(36)
        .nodePadding(290)
        .size([width, height]);
    

      // Constructs a new Sankey generator with the default settings.
      // Using the nodes and links from our data
      sankey
          .nodes(nodes)
          .links(links)
          .layout(32);
    
      // Add in the links
      var link = svg.append("g")
        .selectAll(".link")
        .data(links)
        .enter()
        .append("path")
          .attr("class", "link")
          .attr("d", sankey.link() )
          .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" + (d.value); });
        
      // Add Link Interactivity 
      link.on("click", function(d){
            console.log(d);
            alert("From:  " + d.source.name +" To:"  +d.target.name   +" Value:"+d.value);
          })
    
      // add in the nodes
      var node = svg.append("g")
        .selectAll(".node")
        .data(nodes)
        .enter().append("g")
          .attr("class",...