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">
      .line { fill: none; stroke: black; stroke-width: 6px; }
      .node { fill: white; stroke: black; stroke-width: 2px; }
      .label { font-size: 14px; text-anchor: middle; }
      svg { width: 640px; height: 480px; border: 1px solid black; background-color: #fff; }
    </style>
  </head>
  <body>
    <h1>ツリーレイアウト</h1>
    <svg id="myGraph"></svg>
    <script src="./sample_ex3.js" charset="utf-8"></script>
  </body>
</html>
var dataset = {
  name: "本社",
  children: [
    { name: "経理部" },
    { name: "業務部" },
    {
      name: "開発室",
      children: [
        { name: "情報課" },
        { name: "品質課" },
        {
          name: "開発課",
          children: [
            { name: "ウェブ" },
            { name: "アプリ" }
          ]
        }
      ]
    }
  ]
};

var svgEle = document.getElementById("myGraph");
var svgWidth = parseFloat(window.getComputedStyle(svgEle, null).getPropertyValue("width"));
var svgHeight = parseFloat(window.getComputedStyle(svgEle, null).getPropertyValue("height"));
var offsetLeft = svgWidth / 2 - 100;
var offsetTop = 50;
var offsetBottom = 40;
var nSize = 25;

var tree = d3.layout.tree()
  .size([svgWidth, svgHeight - offsetTop - offsetBottom])
  .nodeSize([120, 110]);

var nodes = tree.nodes(dataset);

// ノードを繋ぐ線
d3.select("#myGraph")
  .selectAll("path")
  .data(tree.links(nodes))
  .enter()
  .append("path")
  .attr("class", "line")
  .attr("d", d3.svg.diagonal())
  .attr("transform", "translate(" + offsetLeft + ", " + offsetTop + ")");

// ノードに丸を表示
d3.select("#myGraph")
  .selectAll("circle")
  .data(nodes)
  .enter()
  .append("circle")
  .attr("class", "node")
  .attr("cx", function(d) { return d.x + offsetLeft; })
  .attr("cy", function(d) { return d.y + offsetTop; })
  .attr("r", nSize);

// ノードにテキストを表示
d3.select("#myGraph")
  .selectAll("text")
  .data(nodes)
  .enter()
  .append("text")
  .attr("class", "label")
  .attr("x", function(d) { return d.x + offsetLeft; })
  .attr("y", function(d) { return d.y + offsetTop; })
  .attr("dy", 6)
  .text(function(d) { return d.name; });

f:id:yossk:20150623211644j:plain