Advertisement
Guest User

D3 force layout example

a guest
Sep 14th, 2011
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.16 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3.   <head>
  4.     <title>Force-Directed Layout (Multiple Foci)</title>
  5.     <script type="text/javascript" src="../../d3.js"></script>
  6.     <script type="text/javascript" src="../../d3.geom.js"></script>
  7.     <script type="text/javascript" src="../../d3.layout.js"></script>
  8.     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
  9.   </head>
  10.   <body>
  11.     <div id="chart"></div>
  12.     <input type="checkbox" name="chkBox" id="chkBox"></input>
  13.     <script type="text/javascript">
  14.  
  15. var w = 960,
  16.     h = 500,
  17.     fill = d3.scale.category10(),
  18.     nodes = d3.range(100).map(Object);
  19.  
  20. var vis = d3.select("#chart").append("svg:svg")
  21.     .attr("width", w)
  22.     .attr("height", h);
  23.  
  24. var force = d3.layout.force()
  25.     .nodes(nodes)
  26.     .links([])
  27.     .size([w, h])
  28.     .start();
  29.  
  30. var node = vis.selectAll("circle.node")
  31.     .data(nodes)
  32.   .enter().append("svg:circle")
  33.     .attr("class", "node")
  34.     .attr("cx", function(d) { return d.x; })
  35.     .attr("cy", function(d) { return d.y; })
  36.     .attr("r", 8)
  37.     .style("fill", function(d, i) { return fill(i & 3); })
  38.     .style("stroke", function(d, i) { return d3.rgb(fill(i & 3)).darker(2); })
  39.     .style("stroke-width", 1.5)
  40.     .call(force.drag);
  41.  
  42. vis.style("opacity", 1e-6)
  43.   .transition()
  44.     .duration(1000)
  45.     .style("opacity", 1);
  46.  
  47. $("#chkBox").change(function(){
  48.   if ($(this).is(':checked')) {
  49.     force.on("tick", tick1);
  50.   } else {
  51.     force.on("tick", tick2);
  52.   }
  53. });
  54.  
  55.  
  56. tick1 = function(e) {
  57.   // Push different nodes in different directions for clustering.
  58.   var k = 6 * e.alpha;
  59.   nodes.forEach(function(o, i) {
  60.     o.x += i & 2 ? k : -k;
  61.     o.y += i & 1 ? k : -k;
  62.   });
  63.  
  64.   node.attr("cx", function(d) { return d.x; })
  65.       .attr("cy", function(d) { return d.y; });
  66. };
  67.  
  68. tick2 = function(e) {
  69.   node.attr("cx", function(d) { return d.x; })
  70.       .attr("cy", function(d) { return d.y; });
  71. };
  72.  
  73. d3.select("body").on("click", function() {
  74.   nodes.forEach(function(o, i) {
  75.     o.x += (Math.random() - .5) * 40;
  76.     o.y += (Math.random() - .5) * 40;
  77.   });
  78.   force.resume();
  79. });
  80.  
  81.     </script>
  82.   </body>
  83. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement