block by emeeks f301b72b3e1f2cfc9bc8

Ch. 11, Fig. 9 - D3.js in Action

Full Screen

This is the code for Chapter 11, Figure 9 from D3.js in Action drawing a force-directed network visualization with 3000 nodes and 1000 edges.

index.html

<html>
<head>
  <title>D3 in Action Chapter 11 - Example 5</title>
  <meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<style>
body, html {
    margin: 0;
  }
canvas {
  position: absolute;
  width: 500px;
  height: 500px;
}
svg {
  position: absolute;
  width:500px;
  height:500px;
}
path.country {
    fill: gray;
    stroke-width: 1;
    stroke: black;
    opacity: .5;
}
path.sample {
    stroke: black;
    stroke-width: 1px;
    fill: red;
    fill-opacity: .5;
}
line.link {
      stroke-width: 1px;
      stroke: black;
      stroke-opacity: .5;
}
circle.node {
  fill: red;
  stroke: white;
  stroke-width: 1px;
}
circle.xy {
  fill: pink;
  stroke: black;
  stroke-width: 1px;
}
</style>
<body>
<canvas height="500" width="500"></canvas>
<div id="viz">
  <svg></svg>
</div>
</body>
  <footer>
    
<script>
  var linkScale = d3.scale.linear().domain([0,.9,.95,1]).range([0,10,100,1000]);

  sampleNodes = d3.range(3000).map(function(d) {
    var datapoint = {};
    datapoint.id = "Sample Node " + d;

    return datapoint;
  })
  sampleLinks = [];
    var y = 0;
    while (y < 1000) {
      var randomSource = Math.floor(Math.random() * 1000);
      var randomTarget = Math.floor(linkScale(Math.random()));
      var linkObject = {source: sampleNodes[randomSource], target: sampleNodes[randomTarget]}
      if (randomSource != randomTarget) {
       sampleLinks.push(linkObject);
      }
      y++;
  }
  
      force = d3.layout.force()
      .size([500,500])
      .gravity(.5)
      .nodes(sampleNodes)
      .links(sampleLinks)
      .on("tick", forceTick);
      
      d3.select("svg").selectAll("line.link")
      .data(sampleLinks)
      .enter()
      .append("line")
      .attr("class", "link")
      .style("stroke-width", "1px")
      .style("stroke", "black")
      .style("stroke-opacity", .5);

      d3.select("svg").selectAll("circle.node")
      .data(sampleNodes)
      .enter()
      .append("circle")
      .attr("r", 3)
      .style("fill", "red")
      .attr("class", "node")
      .style("stroke", "white")
      .style("stroke-width", "1px");
      
      force.start();
      
      function forceTick() {
        d3.selectAll("line.link")
        .attr("x1", function(d) {return d.source.x})
        .attr("y1", function(d) {return d.source.y})
        .attr("x2", function(d) {return d.target.x})
        .attr("y2", function(d) {return d.target.y});

        d3.selectAll("circle.node")
        .attr("cx", function(d) {return d.x})
        .attr("cy", function(d) {return d.y});
      }
      
</script>
  </footer>

</html>