block by curran e6d9643372d3c1f5d42a

D3 Stack Layout

Full Screen

This is a small code example that shows what d3.layout.stack does. It adds y and y0 properties to your data, where y0 is the cumulative sum of y values. This is example 11 from the screencast Splitting Charts.

MIT License

web counter

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
  </head>
  <body>
    <script>

      var yColumn = "population";
     
      function render(data){

        var stack = d3.layout.stack()
          .y(function (d){
            return d[yColumn];
          })
          .values(function (d){
            return [d];
          });

        var stacked = stack(data);

        d3.select("body").append("pre")
          .text(JSON.stringify(stacked, null, 2));
      }

      function type(d){
        d.population = +d.population;
        return d;
      }

      d3.csv("religionWorldTotals.csv", type, render);

    </script>
  </body>
</html>

religionWorldTotals.csv

religion,population
Christian,2173100000
Muslim,1598360000
Unaffiliated,1126280000
Hindu,1032860000
Buddhist,487320000
Folk Religions,404890000
Other Religions,57770000
Jewish,13640000