Guest User

D3 graph

a guest
May 29th, 2013
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <style>
  4.  
  5. .link {
  6.   stroke: #ccc;
  7. }
  8.  
  9. .node text {
  10.   pointer-events: none;
  11.   font: 10px sans-serif;
  12. }
  13.  
  14. </style>
  15. <body>
  16. <script src="http://d3js.org/d3.v3.min.js"></script>
  17. <script>
  18.  
  19. var width = 960,
  20.     height = 500
  21.  
  22. var svg = d3.select("body").append("svg")
  23.     .attr("width", width)
  24.     .attr("height", height);
  25.  
  26. var force = d3.layout.force()
  27.     .gravity(.05)
  28.     .distance(100)
  29.     .charge(-100)
  30.     .size([width, height]);
  31.  
  32. d3.json("graph.json", function(error, json) {
  33.   force
  34.       .nodes(json.nodes)
  35.       .links(json.links)
  36.       .start();
  37.  
  38.   var link = svg.selectAll(".link")
  39.       .data(json.links)
  40.     .enter().append("line")
  41.       .attr("class", "link");
  42.  
  43.   var node = svg.selectAll(".node")
  44.       .data(json.nodes)
  45.     .enter().append("g")
  46.       .attr("class", "node").on("click",function(d) { alert(d.name) })
  47.       .call(force.drag);
  48.  
  49.   node.append("image")
  50.       .attr("xlink:href", "https://github.com/favicon.ico")
  51.       .attr("x", -8)
  52.       .attr("y", -8)
  53.       .attr("width", 16)
  54.       .attr("height", 16);
  55.  
  56.   node.append("text")
  57.       .attr("dx", 12)
  58.       .attr("dy", ".35em")
  59.       .text(function(d) { return d.name });
  60.  
  61.   force.on("tick", function() {
  62.     link.attr("x1", function(d) { return d.source.x; })
  63.         .attr("y1", function(d) { return d.source.y; })
  64.         .attr("x2", function(d) { return d.target.x; })
  65.         .attr("y2", function(d) { return d.target.y; });
  66.  
  67.     node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
  68.   });
  69. });
  70.  
  71. </script>
  72. </body>
Advertisement
Add Comment
Please, Sign In to add comment