force_test.html 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <style>
  4. .node {
  5. stroke: #fff;
  6. stroke-width: 1.5px;
  7. }
  8. .link {
  9. fill: none;
  10. stroke: #bbb;
  11. }
  12. </style>
  13. <body>
  14. <script src="//d3js.org/d3.v3.min.js"></script>
  15. <script>
  16. var width = 960,
  17. height = 500;
  18. var color = d3.scale.category20();
  19. var force = d3.layout.force()
  20. .linkDistance(10)
  21. .linkStrength(2)
  22. .size([width, height]);
  23. var svg = d3.select("body").append("svg")
  24. .attr("width", width)
  25. .attr("height", height);
  26. d3.json("/mbostock/raw/4062045/miserables.json", function(error, graph) {
  27. if (error) throw error;
  28. var nodes = graph.nodes.slice(),
  29. links = [],
  30. bilinks = [];
  31. graph.links.forEach(function(link) {
  32. var s = nodes[link.source],
  33. t = nodes[link.target],
  34. i = {}; // intermediate node
  35. nodes.push(i);
  36. links.push({source: s, target: i}, {source: i, target: t});
  37. bilinks.push([s, i, t]);
  38. });
  39. force
  40. .nodes(nodes)
  41. .links(links)
  42. .start();
  43. var link = svg.selectAll(".link")
  44. .data(bilinks)
  45. .enter().append("path")
  46. .attr("class", "link");
  47. var node = svg.selectAll(".node")
  48. .data(graph.nodes)
  49. .enter().append("circle")
  50. .attr("class", "node")
  51. .attr("r", 5)
  52. .style("fill", function(d) { return color(d.group); })
  53. .call(force.drag);
  54. node.append("title")
  55. .text(function(d) { return d.name; });
  56. force.on("tick", function() {
  57. link.attr("d", function(d) {
  58. return "M" + d[0].x + "," + d[0].y
  59. + "S" + d[1].x + "," + d[1].y
  60. + " " + d[2].x + "," + d[2].y;
  61. });
  62. node.attr("transform", function(d) {
  63. return "translate(" + d.x + "," + d.y + ")";
  64. });
  65. });
  66. });
  67. </script>