block by fogonwater b876949edff0a98b1a2f1b185d6d7245

NZ Sankey Energy tests 2

Full Screen

The above example is intended to demonstrate drawing a simple Sankey diagram using v4 of d3.js. It uses Jason Davies’ version of the Sankey plugin.

This is one of the code samples for the update to the book D3 Tips and Tricks to version 4 of d3.js.

forked from d3noob‘s block: Sankey Diagram with v4

forked from fogonwater‘s block: NZ Sankey Energy tests

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>NZ Energy tests</title>
<style>

body {
  font-family: Helvetica;
  font-size:0.8em;
 }
  
.node rect {
  cursor: move;
  fill-opacity: .9;
  shape-rendering: crispEdges;
}

.node text {
  pointer-events: none;
  text-shadow: 0 1px 0 #fff;
}

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

.link:hover {
  stroke-opacity: .5;
}

</style>
<body>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="sankey.js"></script>
<script>
	
var units = "PJ";

// set the dimensions and margins of the graph
var margin = {top: 10, right: 10, bottom: 10, left: 10},
    width = 950 - margin.left - margin.right,
    height = 900 - margin.top - margin.bottom;

// format variables
var formatNumber = d3.format(",.2f"),    // comma with 1 dp
    format = function(d) { return formatNumber(d) + " " + units; },
    color = d3.scaleOrdinal(d3.schemeCategory20);

// append the svg object to the body of 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 + ")");

// Set the sankey diagram properties
var sankey = d3.sankey()
    .nodeWidth(36)
    .nodePadding(15)
    .size([width, height]);

var path = sankey.link();

// load the data
d3.json("sankey.json", function(error, graph) {

  sankey
      .nodes(graph.nodes)
      .links(graph.links)
      .layout(50);

// add in the links
  var link = svg.append("g").selectAll(".link")
      .data(graph.links.filter((d)=> d.group != 'Ignore'))
    .enter().append("path")
      .attr("class", "link")
      .attr("d", path)
      .style("stroke-width", function(d) {return Math.max(1, d.dy); })
  		.style("stroke", (d) => color(d.group))
      .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); });

// add in the nodes
  var node = svg.append("g").selectAll(".node")
      .data(graph.nodes.filter((d)=> d.group != 'Ignore'))
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { 
		  return "translate(" + d.x + "," + d.y + ")"; })
      .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", (d) => color(d.group))
      //.style("stroke", (d) => d3.rgb(d.color).darker(2))
    .append("title")
      .text(function(d) { 
		  return d.name + "\n" + format(d.value); });

// add in the title for the nodes
  node.append("text")
      .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 + " " + formatNumber(d.value); })
    .filter(function(d) { return d.x < width / 2; })
      .attr("x", 6 + sankey.nodeWidth())
      .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);
  }
});

</script>

</body>

sankey.js

d3.sankey = function() {
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      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.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 = d3.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(
        d3.sum(node.sourceLinks, value),
        d3.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;

    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          if (nextNodes.indexOf(link.target) < 0) {
            nextNodes.push(link.target);
          }
        });
      });
      remainingNodes = nextNodes;
      ++x;
    }

    //
    moveSinksRight(x);
    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }

  function moveSourcesRight() {
    nodes.forEach(function(node) {
      if (!node.targetLinks.length) {
        node.x = d3.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 = d3.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3.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 = d3.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / d3.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, breadth) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            var y = d3.sum(node.targetLinks, weightedSource) / d3.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 = d3.sum(node.sourceLinks, weightedTarget) / d3.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;
};

sankey.json

{
  "links": [
    {
      "group": "coal",
      "source": 0,
      "target": 1,
      "value": 72.91
    },
    {
      "group": "coal",
      "source": 2,
      "target": 1,
      "value": 10.16
    },
    {
      "group": "coal",
      "source": 1,
      "target": 3,
      "value": 37.83
    },
    {
      "group": "coal",
      "source": 4,
      "target": 1,
      "value": 6.85
    },
    {
      "group": "coal",
      "source": 1,
      "target": 5,
      "value": 52.09
    },
    {
      "group": "coal",
      "source": 5,
      "target": 6,
      "value": 25.51
    },
    {
      "group": "coal",
      "source": 6,
      "target": 7,
      "value": 23.5853498518822
    },
    {
      "group": "coal",
      "source": 5,
      "target": 8,
      "value": 11.7029802832
    },
    {
      "group": "coal",
      "source": 5,
      "target": 9,
      "value": 12.3329269618
    },
    {
      "group": "coal",
      "source": 5,
      "target": 10,
      "value": 2.53954240224588
    },
    {
      "group": "coal",
      "source": 6,
      "target": 11,
      "value": 1.51641500232235
    },
    {
      "group": "coal",
      "source": 6,
      "target": 12,
      "value": 1.22967892703738
    },
    {
      "group": "coal",
      "source": 6,
      "target": 13,
      "value": 0.344830082219614
    },
    {
      "group": "coal",
      "source": 6,
      "target": 14,
      "value": 0.00203452815635588
    },
    {
      "group": "renew",
      "source": 15,
      "target": 16,
      "value": 201.842188349912
    },
    {
      "group": "renew",
      "source": 16,
      "target": 9,
      "value": 194.19161113316798
    },
    {
      "group": "renew",
      "source": 17,
      "target": 18,
      "value": 93.2560248967486
    },
    {
      "group": "renew",
      "source": 18,
      "target": 9,
      "value": 93.2560248967486
    },
    {
      "group": "renew",
      "source": 19,
      "target": 20,
      "value": 58.2725728809738
    },
    {
      "group": "renew",
      "source": 21,
      "target": 7,
      "value": 50.0563513833349
    },
    {
      "group": "renew",
      "source": 21,
      "target": 13,
      "value": 8.77924198800265
    },
    {
      "group": "renew",
      "source": 22,
      "target": 23,
      "value": 8.31857884522661
    },
    {
      "group": "renew",
      "source": 23,
      "target": 9,
      "value": 8.31857884522661
    },
    {
      "group": "renew",
      "source": 20,
      "target": 9,
      "value": 4.655398534704
    },
    {
      "group": "renew",
      "source": 24,
      "target": 25,
      "value": 2.71299534443175
    },
    {
      "group": "renew",
      "source": 21,
      "target": 12,
      "value": 2.52764695342229
    },
    {
      "group": "renew",
      "source": 25,
      "target": 9,
      "value": 2.3827337044317503
    },
    {
      "group": "renew",
      "source": 26,
      "target": 9,
      "value": 0.9677179296
    },
    {
      "group": "renew",
      "source": 21,
      "target": 11,
      "value": 0.5987728782537
    },
    {
      "group": "renew",
      "source": 27,
      "target": 28,
      "value": 0.55012484128
    },
    {
      "group": "renew",
      "source": 28,
      "target": 9,
      "value": 0.18612484128
    },
    {
      "group": "renew",
      "source": 29,
      "target": 30,
      "value": 0.1297618163
    },
    {
      "group": "renew",
      "source": 31,
      "target": 9,
      "value": 0.0415153152
    },
    {
      "group": "renew",
      "source": 16,
      "target": 21,
      "value": 7.650577216744011
    },
    {
      "group": "renew",
      "source": 20,
      "target": 21,
      "value": 53.6171743462698
    },
    {
      "group": "renew",
      "source": 25,
      "target": 21,
      "value": 0.3302616399999998
    },
    {
      "group": "renew",
      "source": 28,
      "target": 21,
      "value": 0.36400000000000005
    },
    {
      "group": "renew",
      "source": 30,
      "target": 21,
      "value": 0.1297618163
    },
    {
      "group": "gas",
      "source": 32,
      "target": 33,
      "value": 191.711482912155
    },
    {
      "group": "gas",
      "source": 33,
      "target": 7,
      "value": 65.7357550527379
    },
    {
      "group": "gas",
      "source": 33,
      "target": 9,
      "value": 37.7614082274
    },
    {
      "group": "gas",
      "source": 32,
      "target": 34,
      "value": 12.105877
    },
    {
      "group": "gas",
      "source": 33,
      "target": 12,
      "value": 8.1170846088
    },
    {
      "group": "gas",
      "source": 33,
      "target": 13,
      "value": 6.359754884
    },
    {
      "group": "gas",
      "source": 32,
      "target": 35,
      "value": 6.08504868784498
    },
    {
      "group": "gas",
      "source": 33,
      "target": 11,
      "value": 1.605870431
    },
    {
      "group": "gas",
      "source": 32,
      "target": 36,
      "value": 0.966338119
    },
    {
      "group": "gas",
      "source": 33,
      "target": 14,
      "value": 0.01619479
    },
    {
      "group": "electricity",
      "source": 9,
      "target": 37,
      "value": 153.32523905299996
    },
    {
      "group": "electricity",
      "source": 37,
      "target": 13,
      "value": 44.01958529
    },
    {
      "group": "electricity",
      "source": 37,
      "target": 12,
      "value": 34.328962
    },
    {
      "group": "electricity",
      "source": 37,
      "target": 7,
      "value": 52.286727823
    },
    {
      "group": "electricity",
      "source": 37,
      "target": 11,
      "value": 9.234959447
    },
    {
      "group": "electricity",
      "source": 37,
      "target": 38,
      "value": 11.029882872000002
    },
    {
      "group": "electricity",
      "source": 37,
      "target": 39,
      "value": 0.444780426
    },
    {
      "group": "oil",
      "source": 40,
      "target": 41,
      "value": 82.49
    },
    {
      "group": "oil",
      "source": 42,
      "target": 41,
      "value": 353.8
    },
    {
      "group": "oil",
      "source": 43,
      "target": 14,
      "value": 217.74833275700001
    },
    {
      "group": "oil",
      "source": 43,
      "target": 11,
      "value": 18.978621454
    },
    {
      "group": "oil",
      "source": 43,
      "target": 7,
      "value": 19.987096126
    },
    {
      "group": "oil",
      "source": 43,
      "target": 12,
      "value": 6.792869294
    },
    {
      "group": "oil",
      "source": 43,
      "target": 13,
      "value": 3.3883199639999995
    },
    {
      "group": "oil",
      "source": 43,
      "target": 37,
      "value": 0.02322498
    },
    {
      "group": "oil",
      "source": 43,
      "target": 44,
      "value": 4.62
    },
    {
      "group": "oil",
      "source": 43,
      "target": 45,
      "value": 7.33
    },
    {
      "group": "oil",
      "source": 43,
      "target": 46,
      "value": 10.41
    },
    {
      "group": "oil",
      "source": 43,
      "target": 47,
      "value": 4.08
    },
    {
      "group": "oil",
      "source": 41,
      "target": 48,
      "value": 72.58
    },
    {
      "group": "oil",
      "source": 41,
      "target": 49,
      "value": 8.74
    },
    {
      "group": "oil",
      "source": 41,
      "target": 50,
      "value": 61.7
    },
    {
      "group": "oil",
      "source": 41,
      "target": 43,
      "value": 293.7
    }
  ],
  "nodes": [
    {
      "group": "coal",
      "name": "coal production",
      "node": 0
    },
    {
      "group": "coal",
      "name": "coal primary",
      "node": 1
    },
    {
      "group": "coal",
      "name": "coal imports",
      "node": 2
    },
    {
      "group": "coal",
      "name": "coal exports",
      "node": 3
    },
    {
      "group": "coal",
      "name": "coal oil stock change",
      "node": 4
    },
    {
      "group": "coal",
      "name": "coal supply",
      "node": 5
    },
    {
      "group": "coal",
      "name": "coal demand",
      "node": 6
    },
    {
      "group": "mixed",
      "name": "industrial",
      "node": 7
    },
    {
      "group": "coal",
      "name": "other transformation",
      "node": 8
    },
    {
      "group": "mixed",
      "name": "electricity transformation",
      "node": 9
    },
    {
      "group": "coal",
      "name": "production losses and own use",
      "node": 10
    },
    {
      "group": "mixed",
      "name": "agriculture",
      "node": 11
    },
    {
      "group": "mixed",
      "name": "commercial",
      "node": 12
    },
    {
      "group": "mixed",
      "name": "residential",
      "node": 13
    },
    {
      "group": "mixed",
      "name": "transport",
      "node": 14
    },
    {
      "group": "renew",
      "name": "geothermal supply",
      "node": 15
    },
    {
      "group": "renew",
      "name": "geothermal production",
      "node": 16
    },
    {
      "group": "renew",
      "name": "hydro supply",
      "node": 17
    },
    {
      "group": "renew",
      "name": "hydro production",
      "node": 18
    },
    {
      "group": "renew",
      "name": "woody biomass supply",
      "node": 19
    },
    {
      "group": "renew",
      "name": "woody biomass production",
      "node": 20
    },
    {
      "group": "renew",
      "name": "renew demand",
      "node": 21
    },
    {
      "group": "renew",
      "name": "wind supply",
      "node": 22
    },
    {
      "group": "renew",
      "name": "wind production",
      "node": 23
    },
    {
      "group": "renew",
      "name": "biogas supply",
      "node": 24
    },
    {
      "group": "renew",
      "name": "biogas production",
      "node": 25
    },
    {
      "group": "renew",
      "name": "sludge biogas production",
      "node": 26
    },
    {
      "group": "renew",
      "name": "solar supply",
      "node": 27
    },
    {
      "group": "renew",
      "name": "solar production",
      "node": 28
    },
    {
      "group": "renew",
      "name": "liquid biofuels supply",
      "node": 29
    },
    {
      "group": "renew",
      "name": "liquid biofuels production",
      "node": 30
    },
    {
      "group": "renew",
      "name": "landfill biogas production",
      "node": 31
    },
    {
      "group": "gas",
      "name": "gas gross production",
      "node": 32
    },
    {
      "group": "gas",
      "name": "gas net production",
      "node": 33
    },
    {
      "group": "gas",
      "name": "gas reinjected",
      "node": 34
    },
    {
      "group": "gas",
      "name": "lpg extracted",
      "node": 35
    },
    {
      "group": "gas",
      "name": "gas stock change",
      "node": 36
    },
    {
      "group": "mixed",
      "name": "electricity generation",
      "node": 37
    },
    {
      "group": "electricity",
      "name": "lines losses",
      "node": 38
    },
    {
      "group": "electricity",
      "name": "unallocated",
      "node": 39
    },
    {
      "group": "oil",
      "name": "oil production",
      "node": 40
    },
    {
      "group": "oil",
      "name": "oil primary",
      "node": 41
    },
    {
      "group": "oil",
      "name": "oil imports",
      "node": 42
    },
    {
      "group": "oil",
      "name": "oil supply",
      "node": 43
    },
    {
      "group": "oil",
      "name": "fuel production",
      "node": 44
    },
    {
      "group": "oil",
      "name": "losses and own use",
      "node": 45
    },
    {
      "group": "oil",
      "name": "non-energy use",
      "node": 46
    },
    {
      "group": "oil",
      "name": "stat diff",
      "node": 47
    },
    {
      "group": "oil",
      "name": "oil exports",
      "node": 48
    },
    {
      "group": "oil",
      "name": "oil stock change",
      "node": 49
    },
    {
      "group": "oil",
      "name": "international transport",
      "node": 50
    }
  ]
}