D3.js

データビジュアライゼーションのためのD3.js徹底入門 Webで魅せるグラフ&チャートの作り方

データビジュアライゼーションのためのD3.js徹底入門 Webで魅せるグラフ&チャートの作り方

付録 積み上げ棒フラグ。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Sample</title>
    <script src="../node_modules/d3/d3.min.js" charset="utf-8"></script>
    <style media="screen">
      .forceLine { stroke: red; stroke-width: 5; }
      svg { width: 320px; height: 240px; border: 1px solid black; background-color: #fff; }
    </style>
  </head>
  <body>
    <h1>積み上げグラフ</h1>
    <svg id="myGraph"></svg>
    <script src="./sample_ex2.js" charset="utf-8"></script>
  </body>
</html>
var svgEle = document.getElementById("myGraph");
var svgWidth = parseFloat(window.getComputedStyle(svgEle, null).getPropertyValue("width"));
var svgHeight = parseFloat(window.getComputedStyle(svgEle, null).getPropertyValue("height"));
var barWidth = 50;
var colors = ["red", "pink", "orange"];
var step = 80;
var offsetX = 10;

var dataset = [
  [
    { year: 2010, p: 18 },
    { year: 2011, p: 22 },
    { year: 2012, p: 30 },
    { year: 2013, p: 40 }
  ],
  [
    { year: 2010, p: 12 },
    { year: 2011, p: 25 },
    { year: 2012, p: 45 },
    { year: 2013, p: 80 }
  ],
  [
    { year: 2010, p: 10 },
    { year: 2011, p: 15 },
    { year: 2012, p: 20 },
    { year: 2013, p: 25 }
  ]
];

var stack = d3.layout.stack()
  .y(function(d) { return d.p; });

d3.select("#myGraph")
  .selectAll("g")
  .data(stack(dataset))
  .enter()
  .append("g")
  .attr("fill", function(d, i) {
    return colors[i];
  })
  .selectAll("rect")
  .data(function(d, i) {
    return d;
  })
  .enter()
  .append("rect")
  .attr("x", function(d, i) {
    return offsetX + i * step;
  })
  .attr("y", function(d, i) {
    return svgHeight - d.y0 - d.y;
  })
  .attr("width", barWidth)
  .attr("height", function(d, i) {
    return d.y;
  });

f:id:yossk:20150621155925j:plain